Dan Pickard
Dan Pickard

Reputation: 463

Regex to return false when string that may contain other capital letters other than the first character

So far I've got ^[A-Z]{1}[^A-Z]+

Which works with, for example, John

However it also works for JohnSmith when I want the match to return false if this is the case and the string contains another Capital letter within it

Upvotes: 1

Views: 75

Answers (3)

gfkri
gfkri

Reputation: 2179

In case you need to accept a single capitol letter as well:

^[A-Z][^A-Z]*$

Othwise use

^[A-Z][^A-Z]+$

which accepts a capitol letter with at least one non-capitol letter appended.

Upvotes: 2

Tim Pietzcker
Tim Pietzcker

Reputation: 336498

Your regex matches John as a substring of JohnSmith, so you either need to use an additional end-of-string anchor ($) or choose a regex function that forces the entire string to match. Since not all languages have such a function, here's a solution with anchors:

^[A-Z][^A-Z]+$

Upvotes: 2

vks
vks

Reputation: 67998

^[A-Z][^A-Z]+$

Just add $ anchor to make sure it matches the whole and there are no partial matches.See demo.

https://regex101.com/r/xO3rH2/3

Without $ your regex make a partial match upto John in JohnSmith

Upvotes: 3

Related Questions