Home > Software design >  How do I negate this Regular Expression?
How do I negate this Regular Expression?

Time:08-29

I found this Regular Expression which only matches for valid coordinates.

^[- ]?([1-8]?\d(\.\d )?|90(\.0 )?),\s*[- ]?(180(\.0 )?|((1[0-7]\d)|([1-9]?\d))(\.\d )?)$

(Which I found from here)

How do I negate it so it matches anything that isn't a valid coordinate? I've tried using ?! but not matter where I put it, it doesn't seem to work

Edit: Edited the Regular Expression because I didn't copy it correctly

CodePudding user response:

If you want to negate a whole regex like this you'd better not try to phrase this inside the regular expression. The programming language you use (in your case javascript) will have a function to match against a string. (i gues in your case its string.matches(regex) just negate that expression !string.matches(regex).

If you want to have the whole text without the coordinates then you could do string.replaceAll(regex, "") and you get the text without the matching components.

CodePudding user response:

The negation by wrapping all in a ^(?! ) construct will work, but your regex is not correct -- you lost some essential characters, so that it has ,* making the comma optional so that many single numbers will also be matched. The original (correct) regex has ,\s* at that position in the regex. If you don't want to allow such white space, then remove \s*, not just \s...

So the opposite test can be done with:

^(?![- ]?([1-8]?\d(\.\d )?|90(\.0 )?),\s*[- ]?(180(\.0 )?|((1[0-7]\d)|([1-9]?\d))(\.\d )?)$)

If you actually want to capture the line that this regex matches, append .* to this regex.

  • Related