0

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.

1
  • Do you want to replace the matched text with something else? Commented Nov 29, 2016 at 16:37

3 Answers 3

1

Here is one that works even if the @test is at the beginning of the string:

(?:^|[^@])@test

Regex101

Sign up to request clarification or add additional context in comments.

Comments

1

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

0

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

As long as the line does not start with @test.
@SunnyPatel I have edited the answer. Hope it is fine now
A lookbehind has to be a fixed character length. Lengths of 0 and 1 won't work.
@SunnyPatel Sorry I didn't get you. There are no look behinds in the regex. And moreover javascript doesn't support lookbehinds

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.