Jesse Black
Jesse Black

Reputation: 7976

Regex to find a expression followed by whitespace, #, @ or end of input

I want to find all instance of word (say myword), with the added condition that the word has whitespace, "@", "#" afterwords, or is the end of input.

Input string:
"myword# myword mywordrick myword@ myword"

I want the regex to match everything besides mywordtrick -

myword#
myword 
myword@
myword

I am able to match against the first 3 with myword[@#\s]

I thought myword[@#\s\z] would match against all 4, but I only get 3

I try myword[\z] and get no matches I try myword\z and get 1 match.

I figure \z inside a [] doesn't work, because [] is character based logic, rather than position based logic.

Is there a way to use a single regex to match the expressions I am interested in? I do not want to use both myword[#@\s] and myword\z unless I really have to.

Upvotes: 1

Views: 58

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174696

Your regex would be,

myword(?:[@#\s]|$)

It matches the string myword along with the symbols only if it's followed by # or @ or \s or $. $ means the end of the line.

DEMO

Upvotes: 3

Related Questions