Craig Walker Craig Walker - 1 year ago 73
Java Question

Using Regular Expressions to Extract a Value in Java

I have several strings in the rough form:

[some text] [some number] [some more text]

I want to extract the text in [some number] using the Java Regex classes.

I know roughly what regular expression I want to use (though all suggestions are welcome). What I'm really interested in are the Java calls to take the regex string and use it on the source data to produce the value of [some number].

EDIT: I should add that I'm only interested in a single [some number] (basically, the first instance). The source strings are short and I'm not going to be looking for multiple occurrences of [some number].

Answer Source


Pattern p = Pattern.compile("^[a-zA-Z]+([0-9]+).*");
Matcher m = p.matcher("Testing123Testing");

if (m.find()) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download