1

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.

1
  • 1
    Are your numbers known to be integers? or could they contain a decimal point? Commented Feb 10, 2011 at 22:57

1 Answer 1

4
-?\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...

Sign up to request clarification or add additional context in comments.

6 Comments

defintely not for Pattern.compile, where \d doesn't exist. I'm not sure whether this will get me negative values like -1 though...
@wishi - Pattern.compile DOES understand \d; see the javadoc - download.oracle.com/javase/6/docs/api/java/util/regex/…
I just found this regex tester here yesterday and I must say it's by far my favorite so far. Also since you want the integers somewhere in between the string you need something like this: .*?(-?\d+).*
What makes RegexPlanet especially useful is that it actually uses the Java flavor (the RegExLib tester uses .NET, with the option to emulate JavaScript), and it generates a string-literal form of the regex. That's probably why you thought \d wasn't supported, @wishi; in a Java string literal you have to escape the backslash--i.e., "\\d".
@Neil -- are those asterisks are part of regex or you wanted to make it bold?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.