nhaa123
nhaa123

Reputation: 9798

RegEx to match two alternatives but nothing else

I need to capture either

\d+\.\d+

or

\d+

but nothing else.

For instance, "0.02", "1" and "0.50" should match positively. I noticed that I cannot simply use something like

[\d+\.\d+|\d+]

Upvotes: 2

Views: 2754

Answers (3)

cletus
cletus

Reputation: 625087

You can do either:

(\d+|\d+\.\d+)

or

(\d+(\.\d+)?)

but that creates a second capturing group. The more sophisticated version is:

(\d+(?:\.\d+)?)

That's called a non-capturing group.

By the way Regular Expression Info is a superb site for regular expression tutorials and information.

Upvotes: 3

jensgram
jensgram

Reputation: 31508

Or \d+(\.\d+)? if you find that easier to read :)

Upvotes: 0

KiNgMaR
KiNgMaR

Reputation: 1567

(\d+\.\d+|\d+)

should do the trick.

Upvotes: 6

Related Questions