Home > OS >  Regex that include numbers but exlude numbers in dates (xx/xx/xx)
Regex that include numbers but exlude numbers in dates (xx/xx/xx)

Time:11-08

I currently only have the regex that matches all numbers. But I also want to exlude numbers that are in dates

Exlude numbers that are in dates -> 08/11/2022. But include numbers without date.

This is my regex: \d

CodePudding user response:

What differentiate dates and numbers is existence of '/' or '-'. So, you can use negative lookhead after your pattern and negative lookbehind before your pattern.

(?<![\d\-\/])\d (?![\d\-\/])

Check on Regex101

CodePudding user response:

It would be important to know what a date in the string can look like or could look in the future.

If the format is and always will be 08/11/2022 then you could do something like (?<!\/|\d)\d (?!\/|\d).

The negative lookbehind (?<!\/|\d) will prevent capturing digits after a slash or other digits (this is important otherwise only the first digit after the slash will not be captured, \d will still capture multiple digits in a row if there is no slash). The negative lookahead does the same for following slashes and digits.

However this will also prevent capturing digits that are not in dates but are following/followed by slash. Also negative lookbehinds are not supported everywhere.

Probably better to simply remove the dates first by trying to match them specifically:

((\d{1,2})(\/|\.)(\d{1,2})(\/|\.)(\d{4}|\d{2}))

  • Related