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

Discussion in 'Java' started by Jochen Brenzlinger, Nov 21, 2011.

  1. 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 Brenzlinger, Nov 21, 2011
    1. Advertisements

  2. 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;

    public void extractIndex() throws Exception
    String source = "Foo[345]";
    Pattern pattern = Pattern.compile("\\w+\\[(\\d+)\\]");
    Matcher matcher = pattern.matcher(source);
    assertThat(matcher.groupCount(), is(1));
    String index =;
    assertThat(index, is("345"));
    Henk van Voorthuijsen, Nov 21, 2011
    1. Advertisements

  3. Jochen Brenzlinger

    Tassilo Horn Guest

    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(;
    // idx should be 123 here

    Tassilo Horn, Nov 21, 2011
  4. Jochen Brenzlinger

    Roedy Green Guest

    for examples.
    Roedy Green, Nov 21, 2011
  5. Jochen Brenzlinger

    Stefan Ram Guest

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

    java.lang.Long.valueOf( var.replaceAll( "\\D+(\\d+).", "$1" ))
    Stefan Ram, Nov 21, 2011
  6. Jochen Brenzlinger

    Daniel Pitts Guest

    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+)
    Daniel Pitts, Nov 21, 2011
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.