Coder Guy
Coder Guy

Reputation: 325

Need regex help for matching names

Let's say I have these three names

John Doe (p45643)
Le'anne Frank
Molly-Mae Edwards

I want to match 1) John Doe 2) Le'anne Frank 3) Molly-Mae Edwards

The regex I have tried is

(^[a-zA-Z-'^\d]$)+

but it isn't working as I am expecting.

I would like help creating a regex pattern that:

Matches a name from start to finish, and cannot contain a number. The only permitted values each "name" can contain is, [a-zA-Z'-], so if a name was J0hn then it shouldn't match

Upvotes: 0

Views: 50

Answers (3)

Federico Piazza
Federico Piazza

Reputation: 31035

If I understood correctly your question, then you have a minor errors in your regex:

(^[a-zA-Z-'^\d]$)+
         ^-------^------Here

The - pointed above should be escaped or moved to the end since it works as a range character. The + is marking the group as repeated.

You can use this regex instead (following your previous pattern):

(^[a-zA-Z'^\d -]+$)

Regex demo

Update: for your comment. If you want to match separately, then you can use:

(\b[a-zA-Z'^\d-]+\b)

Regex demo

And if you only want to match string (not numbers), then you can use:

(\b[a-zA-Z'-]+\b)

Regex demo

Upvotes: 1

Coder Guy
Coder Guy

Reputation: 325

Thanks to @Djory Krache

The query I was looking for was

(\b[a-zA-Z'-]+\b)

Upvotes: 0

Prashanth
Prashanth

Reputation: 26

You are using the anchors incorrectly. Based on the modifier it can match the whole string or a single line. Try

/^[a-zA-Z'-]+$/

Upvotes: 0

Related Questions