1

I am trying to write a regex for a string which has a format [digit] [to] [digit] eg. 1 to 5 in which if I find a word "to" from a given string i want to extract the number before and after, I have tried this and it's not working.

Pattern p = Pattern.compile("([0-9]+)\\bto\\b([0-9]+)");
        Matcher m = p.matcher("1 to 5");
        m.find();
        System.out.println(m.group(0));
        System.out.println(m.group(1));
        System.out.println(m.group(2));

Expected o/p

1
to
5
6
  • Please clarify "it's not working". Commented Feb 7, 2019 at 8:38
  • 1
    From the documentation "Group zero denotes the entire pattern" Commented Feb 7, 2019 at 8:38
  • ([0-9]+)\\sto\\s([0-9]+) with \s to match whitespaces should work Commented Feb 7, 2019 at 8:39
  • There is no capturing group around to, don't expect to get it in group Commented Feb 7, 2019 at 8:39
  • you asked the same question few min before? - stackoverflow.com/questions/54568814/… Commented Feb 7, 2019 at 9:06

2 Answers 2

3

Consider adding a group for the to part.

Also for the space, you want \\s not \\b:

Pattern p = Pattern.compile("([0-9]+)\\s(to)\\s([0-9]+)");
Matcher m = p.matcher("1 to 5");
m.find();
System.out.println(m.group(1));
System.out.println(m.group(2));
System.out.println(m.group(3));

And as said in the comments :

" Group zero denotes the entire pattern"

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

Comments

0

Is it necessary that you must use regex. If not, you can use String functions.

      String s="23 to 34";
      String toString="to";
      if(s.contains(toString)){
          int startIndex=s.indexOf(toString);
          int endIndex=startIndex+(toString).length();
          String s1=s.substring(0, startIndex); //get the first number
          String s2=s.substring(endIndex);  //get the second number
          System.out.println(s1.trim()); // Removing any whitespaces
          System.out.println(toString);
          System.out.println(s2.trim();
      }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.