Regex: Match all words that start with specific sign until end of the word

Viewed 32

I have a string:

'@test1 in else',
'@test2 in something',

My goal is to receive on regex match the following:

test1
test2

The closest I got is using this but it seems to be not fully working, please help me figure it out, thanks:

(?<=@)(.*)(\s+)
2 Answers

Lookbehind wasn't supported in JavaScript for a long time. It's now part of the ECMAScript 2018 and supported in Google Chrome. So (?<=@) may not work in all Browsers.

in your example (.*) searches for the longest possible match (greedy) with (.*?) you get the shortest possible match (lazy or reluctant)

@(.*?)\s+ or @(\w+) and you'll find your result in the group1 of your match.


https://regex101.com/r/JSwVOk/1
https://regex101.com/r/JSwVOk/2

You could use (?<=@)(\w*) with the \w* that:

Matches any word character (alphanumeric & underscore). Only matches low-ascii characters (no accented or non-roman characters). Equivalent to [A-Za-z0-9_]

But be aware that positive lookbehinds are not supported in all browsers.

https://regexr.com/6tiik

Related