I am figuring how to create a regex that matches @test only when it is not with another @. I have a solution with negative lookbehind, but feature is not supported in JS. Is there a solution without negative lookbehind?
Ex.
This @test should be a match.
This @@test should not be a match.
-
Do you want to replace the matched text with something else?Wiktor Stribiżew– Wiktor Stribiżew2016-11-29 16:37:14 +00:00Commented Nov 29, 2016 at 16:37
Add a comment
|
3 Answers
Here is one that works even if the @test is at the beginning of the string:
(?:^|[^@])@test
Comments
You can exclude with a negative character group preceding @test:
/[^@]@test/
That won't work at the beginning of the line, but will work with your sample text. If you need to worry about the beginning of the line too, you can do this:
/(^|[^@])@test/
This will match @test as the first thing in the line, or @test with some non-@ character preceding it.
Comments
What about a negated character class.
/(?:[^@]|^)@test/
[^@]Matches anything other than a@
Example
"This @@test should not be a match".match(/(?:[^@]|^)@test/)
// null
"This @test should not be a match".match(/(?:[^@]|^)@test/)
// [" @test"]
4 Comments
Sunny Patel
As long as the line does not start with
@test.nu11p01n73R
@SunnyPatel I have edited the answer. Hope it is fine now
Sunny Patel
A lookbehind has to be a fixed character length. Lengths of 0 and 1 won't work.
nu11p01n73R
@SunnyPatel Sorry I didn't get you. There are no look behinds in the regex. And moreover javascript doesn't support lookbehinds