Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 基于另一个字符串从字符串中提取数字_Java - Fatal编程技术网

Java 基于另一个字符串从字符串中提取数字

Java 基于另一个字符串从字符串中提取数字,java,Java,我正在尝试为一个格式为[digit][to][digit]的字符串编写正则表达式,例如1到5,如果我从给定字符串中找到一个单词“to”,我想在前后提取数字,我已经尝试过了,但它不起作用 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));

我正在尝试为一个格式为[digit][to][digit]的字符串编写正则表达式,例如1到5,如果我从给定字符串中找到一个单词“to”,我想在前后提取数字,我已经尝试过了,但它不起作用

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));
预期o/p

1
to
5

考虑为
部件添加一个组

同样对于空间,您希望
\\s
而不是
\\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));
正如评论中所说:

“零组表示整个模式”


您必须使用正则表达式吗。如果没有,可以使用字符串函数

      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();
      }

请澄清“它不起作用”。从“零组表示整个模式”
([0-9]+)\\sto\\s([0-9]+)
\s
匹配空格应该有效
没有捕获组,不要期望在
组中得到它几分钟前你问了同样的问题-