Check if String.matches() AND (if yes) extract number from String?

J

Jochen Brenzlinger

Assume I have a String var and value like:

String var = new String("foobar[345]");

Now I want to check if this string matches a certain pattern and if yes extract the number into a long var.
The first part is easy:

if var.matches("\\w*\[\\d+\]") {
long l = ????; }

....but I have no idea on how to extract the number.
How can this be achieved?

Jochen
 
H

Henk van Voorthuijsen

Basically, you use the java.util.regex classes.

here's a unit test that illustrates the technique:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Test
public void extractIndex() throws Exception
{
String source = "Foo[345]";
Pattern pattern = Pattern.compile("\\w+\\[(\\d+)\\]");
Matcher matcher = pattern.matcher(source);
matcher.find();
assertThat(matcher.groupCount(), is(1));
String index = matcher.group(1);
assertThat(index, is("345"));
}
 
T

Tassilo Horn

Assume I have a String var and value like:

String var = new String("foobar[345]");

Now I want to check if this string matches a certain pattern and if
yes extract the number into a long var.

You are looking for Capturing Groups. Have a look at
java.util.regex.Pattern and Matcher. You need something along these
lines (untested):

String foo = "bla[123]";
Pattern myPattern = Pattern.compile("\\w+\\[(\\d+)\\]");
Matcher m = myPattern.matcher(foo);
if (m.find()) {
long idx = Long.parseLong(m.group(1));
// idx should be 123 here
}

Bye,
Tassilo
 
S

Stefan Ram

if var.matches("\\w*\[\\d+\]") {
long l = ????; }
...but I have no idea on how to extract the number.

When you already know that »var« does match, you can use:

java.lang.Long.valueOf( var.replaceAll( "\\D+(\\d+).", "$1" ))
 
D

Daniel Pitts

if var.matches("\\w*\[\\d+\]") {
long l = ????; }
...but I have no idea on how to extract the number.

When you already know that »var« does match, you can use:

java.lang.Long.valueOf( var.replaceAll( "\\D+(\\d+).", "$1" ))

.
Technically correct specific to this example. However, if you have a
more complicated pattern it won't necessarily work.

For example, \w*\[\d+\](?:\w+(\d+))?\w*(\d+)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top