Haim Lvov
Haim Lvov

Reputation: 1053

Regex to match a string if it matches only one group in Java

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

Answers (2)

Sweeper
Sweeper

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

Michał Turczyn
Michał Turczyn

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

Demo

Upvotes: 9

Related Questions