wishi
wishi

Reputation: 7387

Regex to detect number within String

I'm confronted with a String:

[something] -number OR number [something]

I want to be able to cast the number. I do not know at which position is occures. I cannot build a sub-string because there's no obvious separator.

Is there any method how I could extract the number from the String by matching a pattern like

[-]?[0..9]+

, where the minus is optional? The String can contain special characters, which actually drives me crazy defining a regex.

Upvotes: 1

Views: 813

Answers (1)

Neil Fenwick
Neil Fenwick

Reputation: 6184

-?\b\d+\b

That's broken down by:

-? (optional minus sign)

\b word boundary

\d+ 1 or more digits

[EDIT 2] - nod to Alan Moore

Unfortuantely Java doesn't have verbatim strings, so you'll have to escape the Regex above as:

String regex = "-?\\b\\d+\\b"

I'd also recommend a site like http://regexlib.com/RETester.aspx or a program like Expresso to help you test and design your regular expressions

[EDIT] - after some good comments

If haven't done something like *?(-?\d+).* (from @Voo) because I wasn't sure if you wanted to match the entire string, or just the digits. Both versions should tell you if there are digits in the string, and if you want the actual digits, use the first regex and look for group[0]. There are clever ways to name groups or multiple captures, but that would be a complicated answer to a straight forward question...

Upvotes: 4

Related Questions