Home > Net >  How to use a negative lookahead to prevent my regular expression from matching?
How to use a negative lookahead to prevent my regular expression from matching?

Time:10-27

I'm using this regular expression: ^(\d (?:\.\d )?) that will match any decimal or integer numeric value that is followed by any character and will capture only the numeric part of it. For example this regex will match the following values and capture the numeric part of them:

  • 10.5
  • 10.5 Inches
  • 10 Inches

However, it seems like my regex will also match the following value: 6" 1.5". I want to update my regex so that it doesn't match for these type of values. So it shouldn't match if there are multiple numeric values.

I tried doing a negative lookahead like this ^(\d (?:\.\d )?)(?!\d), but it doesn't seem to be working.

CodePudding user response:

Converting my comment to answer so that solution is easy to find for future visitors.

You may use this regex:

^(\d (?:\.\d )?)\b(?!.*\d)

RegEx Demo

RegEx Breakdown:

  • ^: Line start
  • (: Start a capture group
    • \d : Match 1 digits
    • (?:\.\d )?: Optionally match dot and 1 digits
  • ): End capture group
  • \b: Word boundary
  • (?!.*\d): Negative lookahead to assert that there is no digit ahead after this match
  • Related