Regex: match a string at start or after some special characters

Viewed 269

I'm using Java Pattern class to find a string "keyword" which is at the beginning of the string or after a character that is in a list of characters. For example, the list of characters is ' ' and '<', then:

match:
"keyword..."
"...<keyword..."
"... keyword..."

not match:
"...akeyword..."

I've tried all these:

"[^ <]keyword"
"[ <^]keyword"
"[\\^ <]keyword"  note:for a Java/C# string backslash need to be escaped

This question is similar Match only at string start or after whitespace but with only basic skills of Regex I can't adopt it to this problem. I'v tried:

"(?<!\\S<)keyword"
"(?<!([\\S<]))keyword"

And this seems to be a very basic problem, there may be a very easy and clear way.

3 Answers

This should work (^|[< ])keyword

(...|...) has ^ and [< ], stating either it should be start of string of be after char(<) or char( )

You could use an alternation | in a non capturing group (?:^|[ <]) to assert either the start of the string ^ or match a space or < in a character class and use a capturing group for keyword.

(?:^|[ <])(keyword)\b

Regex demo

Or you could use a positive lookbehind (?<=...) and match only keyword

(?<=^|[< ])keyword\b

Regex demo

(^keyword |[< ^]keyword)

Write in the square brackets the character you need.

Related