I'm trying to extract date, percentage or number from string. Strings can be:
I've written regex as (?:\d{2}\/\d{4}|\d{2}(?:\/\d{2}\/\d{4})?)
Regex is satisfying 12/12/2014, 10, 02/2012.
I'm also trying to modifying same regex to get 10, 08/2015 and 10/10/2015 but not getting how to get.
How can this be achieved?
To match your example data, you could use an alternation matching either 2 digits / 4 digits, or match 2 digits with an optional part that matches 2 digits and 4 digits.
\b(?:\d{2}\/\d{4}|\d{2}(?:\/\d{2}\/\d{4})?)\b
Explanation
\b
Word boundary, prevent the word char being part of a larger word(?:
Non capture group
\d{2}\/\d{4}
Match 2 digits/4 digits|
Or\d{2}
Match 2 digits(?:\/\d{2}\/\d{4})?
Optionally match /2 digits/4 digits)
Close group\b
Word boundaryNote that 2 and 4 digits could also match 99 and 9999. If you want to make your match more specific, this page can be helpful https://www.regular-expressions.info/dates.html
const pattern = /\b(?:\d{2}\/\d{4}|\d{2}(?:\/\d{2}\/\d{4})?)\b/;
[
"the response value 10",
"the response value 10/12/2014",
"the response value 08/2015"
].forEach(s => console.log(s.match(pattern)[0]));
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加