Frenz
Frenz

Reputation: 747

Regex to match string at the starting of text

I have the following RegEx https://www.regex101.com/r/ZvXQmI/2 which would match any word starting with @. It works pretty good however, it doesn't match the string at the start of the text. Appreciate if you could help me on this. Also, RegEx shows it took 1029 steps. If this can be reduce to improve performance, highly appreciate that.

Thanks in advance.

Upvotes: 0

Views: 67

Answers (3)

Ibrahim
Ibrahim

Reputation: 6088

Try this

(?<word>@[a-zA-Z]\w+)(<|\s+)?

Demo: https://www.regex101.com/r/ZvXQmI/3

If you just want words that start with @, You could use something simpler

@[a-zA-Z]\w+

Upvotes: 0

dognose
dognose

Reputation: 20889

Use word-boundaries.

\B(?<word>@[a-zA-Z]\w+)\b

https://www.regex101.com/r/ZvXQmI/4

Effectively, \B matches at any position between two word characters as well as at any position between two non-word characters. (required to exclude the domain, where @ is preceded by a word-character)

Voila, 42 steps, same result.

Upvotes: 2

dawg
dawg

Reputation: 103814

If you only want to match any word starting with @ you can do:

(@\w+)

Demo

That does it in 32 steps. (Or use a word boundary \B(@\w+) if you want more specificity)

If you want to keep your regex and match the word at the beginning, you can add ^ for the beginning of the string like so:

(?:>|\s+|^)(?<word>@[a-zA-Z]\w+)(<|\s+)? 

Demo

Upvotes: 1

Related Questions