Results 1 to 3 of 3

Thread: Java Pattern

  1. #1
    Ginso is offline Member
    Join Date
    Feb 2017
    Posts
    12
    Rep Power
    0

    Default Java Pattern

    Hi,
    i have a text containg parts like "(0 links)", "(619 links)", etc and i want to find these occurences.
    I'm using the Pattern and Matcher from the java.util.regex package:

    Java Code:
    Pattern p = Pattern.compile("\\(*\\d links\\)");
    Matcher m = p.matcher(text);
    boolean b = m.find();
    while(b) {
            String t = text.substring(m.start(), m.end());
            //...
            b=m.find();
    }
    now, in the run of the loop, t is "(0 links)", right as it should be.
    but in the following run it's only "9 links)", instead of "(619 links)". What am i doing wrong?

  2. #2
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,989
    Rep Power
    8

    Default Re: Java Pattern

    Your quantifier is wrong, it should be after the \d. Also, you should be using a group. Note how the \d* is enclosed in ( and ) to make it a group. Then while find(), group(0) is the entire expression, and group(1) is the first group, etc.
    Java Code:
      Pattern p = Pattern.compile("\\((\\d*) links\\)");
            String text = "(619 links)";
            Matcher m = p.matcher(text);
            while(m.find()) {
                String group = m.group(1);
                System.out.println(group);
            }
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  3. #3
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: Java Pattern

    Based on your initial example the qualifier should be \\d+ because I presume you want to guarantee at least one digit. Otherwise
    you could match ( links) if it existed.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

Similar Threads

  1. strategy pattern and bridge pattern
    By jomypgeorge in forum New To Java
    Replies: 2
    Last Post: 12-13-2010, 05:13 AM
  2. Need to print pattern in java
    By Gan in forum New To Java
    Replies: 1
    Last Post: 10-20-2010, 08:36 AM
  3. Class pattern to generate following pattern:-
    By vxs in forum New To Java
    Replies: 5
    Last Post: 07-14-2010, 11:15 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •