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
saurabh kumar
  • 83
  • 1
  • 5

2 Answers2

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"

Arnaud
  • 17,229
  • 3
  • 31
  • 44
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();
      }
Pranav balu
  • 126
  • 1
  • 5