Home > Net >  Regex Numbers that are not proceed by a specific string
Regex Numbers that are not proceed by a specific string

Time:09-22

I have this regex :

(?<!FY)([0-9]{1,4}\.|)(?<!VAC)?([0-9]{1,4})?([A-Z])?(-)([0-9]{1,4})(\.[0-9]{1,2})?(\:[0-9]{1,2})?(\.[0-9]{1,2})?(?!.*?\<\/a\>)

and the following string :

Examine 58.1-609.6 brother prudent add day ham. FY 22-23 stairs now 58.1-439.12:02 oppose hunted become

I want to get :

  • 58.1-609.6

  • 58.1-439.12:02

But not : FY 22-23

CodePudding user response:

To match those numbers in the question, you might use:

(?<!\b(?:FY|VAC)\s*)\b[0-9]{1,4}\.[0-9]-[0-9]{1,4}\.[0-9]{1,2}(?::[0-9]{1,2})?\b

Explanation

  • (?<! Negative lookbehind, assert what is to the left is not
    • \b(?:FY|VAC)\s* match either FY or VAC followed by optional whitspace chars
  • ) Close the lookahead
  • \b[0-9]{1,4}\.[0-9]-[0-9]{1,4} A word boundary, then match 1-4 digits . digit - 1-4 digits
  • \.[0-9]{1,2} Match . 1-2 digits
  • (?::[0-9]{1,2})? Optionally match : and 1 or 2 digits
  • \b A word boundary

See a .NET regex demo.

Then you can extend the pattern to assert not a closing anchor tag to the right with (?!.*?\<\/a\>) or other rules that you want like optional chars [A-Z]?

  • Related