Reputation: 1053
I would like to know, is there a regex that could help match text, only if the tested string belongs only to one of the tested groups?
let's say I have these two groups:
Group 1: [a-zA-Z]
Group 2: [0-9]
So is there an applicable regex, to match only the following string: abc
,
or only this one: 123
.
But that would not match anything, when there is a string that represents a combination of both groups, i.g: 123abc2b
?
P.S: I'm using Java.
Upvotes: 1
Views: 1817
Reputation: 271320
Based on your description, I think you just need |
, which means "or" in regex. To match either [a-zA-Z]
or [0-9]
, but not both.
e.g.
^(?:[a-zA-Z]+|[0-9]+)$
Upvotes: 3
Reputation: 37367
Alternation is key to your problem. Use pattern ^(?:\d*|[a-zA-Z]*)$
Explnation:
^
- beginning of the string
(?:...)
- non-captruing group
\d*
- match zero or more digits
|
- alternation
[a-zA-Z]*
- match zero or more letters (lower or uppercase)
$
- match end of the string
Upvotes: 9