regex to match a string start with a word and end with or without number

Viewed 281

I want to use powershell to search all AD samaccountname start with "jamec" - short form of full name like "Jame Cameron" - and end with number but not include other short form like "jamech"

"jamec" - match "jamec1234" - match "jamec12" - match

"jamech" - not match "jamech12" - not match

tried this "^jamec(\d+)(?!.*\d)" but string without number "jamec" become not match.

2 Answers

Try using:

^jamec\d*$

This matches jamec followed optionally by only one or more digits. If you want to also match other content in the input, then use ^jamec\d*\b instead.

If you want to ensure that the first digit in the optional number does not start with zero, then use:

^jamec(?:[1-9][0-9]*)?$

Demo

The pattern you tried ^jamec(\d+)(?!.*\d) requires that there is at least 1 digit following jamec.

The negative lookahead (?!.*\d) asserts that in all the characters to the right there can not be a digit present.


You could use a word boundary \b and match the digits 0+ times using * instead of +

^jamec\d*\b

Regex demo

To match nothing after the digits, you could also assert a whitespace boundary

^jamec\d*(?!\S)

Regex demo

Related