-2

I created a regex using minimatch library in nodeJs. I wanted to find Date's in the string.

minimatch.makeRe("*/*/*")

It returned

/^(?:(?!\.)(?=.)[^/]*?\/(?!\.)(?=.)[^/]*?\/(?!\.)(?=.)[^/]*?)$/

But when I use the regex in string.search method it is returning 0.

let text = "Some Test Data151.000.0083.680.0046.4020.92 02/03/2000Some Test Data";

console.log(text.search(/^(?:(?!\.)(?=.)[^/]*?\/(?!\.)(?=.)[^/]*?\/(?!\.)(?=.)[^/]*?)$/));

As per the documentation string.search should return the index on which the string is found.

Any suggestions or help will be appreciated.

Shahab Ali
  • 183
  • 1
  • 1
  • 18
  • I don't think minimatch is the right tool for the job, from what I understand. It appears to be a glob matcher when, at least in this simple case, a regex like `\d{2}\/\d{2}\/\d{4}` would suffice. – Julia Jun 04 '22 at 09:06
  • Index of 0 is the first char. * in a wildcard means zero or more characters. – Christopher Jun 04 '22 at 09:13
  • @Julia yup the regex worked, also if I want to find 151.00 and 0.00 or 83.68 where the digits after decimal point are fixed (2 digits) while before decimal point are variable, is a regex like this possible? \d{n}\.\d{2} – Shahab Ali Jun 04 '22 at 09:19
  • `\d{1,}\.\d{2}` will do this. – Christopher Jun 04 '22 at 09:28
  • Can someone tell me how is this question duplicate of https://stackoverflow.com/questions/32949649/find-dates-in-text. It is a totally different question? My question was why the regex from mis-match is not working? – Shahab Ali Jun 04 '22 at 10:18

1 Answers1

1

The regex pattern you are getting will match the entire string no matter what. Most likely because * is treated as wild card which means it will match for zero or more strings.

^(?:(?!\.)(?=.)[^/]*?\/(?!\.)(?=.)[^/]*?\/(?!\.)(?=.)[^/]*?)$ this regex also does the same. That's why you its returning zero. As the first element of the string is getting matched.

For solution change the regex pattern to /\d{2}\/\d{2}\/\d{4}/ if you are sure that dates will appear in dd/mm/yyyy format.

In case the dates may appear in d/m/yyyy or d/m/yy format us \d{1,2}\/\d{1,2}\/\d{2,4} this regex pattern.