Reputation:
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
Upvotes: 0
Views: 252
Reputation: 7616
If you simply want to extract a valid coordinate from a longer string you don't need to negate the regex. You can use this regex replace:
let coord = str.replace(/^.*?([-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)).*$/, '$1');
Explanation:
^.*?
- is a non-greedy scan that will scan up to the first pattern found that follows; if you use ^.*
instead, you'll scan up to the last pattern (in case there is more than one); pick the one you want(
... )
- defines a capture group, anything within the parenthesis is captured and can be referenced as $1
in the replacement; add your regex sans anchors.*$
- eat up anything that is left[\s\S]
instead of .
, e.g. start with ^[\s\S]*?
and end with [\s\S]*$
Upvotes: 0
Reputation: 350252
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.
Upvotes: 0
Reputation: 7855
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.
Upvotes: 1