Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/312.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_Regex - Fatal编程技术网

Java 这个正则表达式模式错了吗?

Java 这个正则表达式模式错了吗?,java,regex,Java,Regex,从这段代码中获得奇怪的输出 捕获组数:3 找到值(capturint组(1)):此订单是针对QT300下的 找到的值(capturint组(2)):0 找到的值(capturint组(3)):!好吗 正则表达式不应该在第一个“3”处中断吗,因为它是所有字符之后的第一个数字 import java.util.regex.Matcher; import java.util.regex.Pattern; public class CaptureGroups1 { public stati

从这段代码中获得奇怪的输出

  • 捕获组数:3
  • 找到值(capturint组(1)):此订单是针对QT300下的
  • 找到的值(capturint组(2)):0
  • 找到的值(capturint组(3)):!好吗
正则表达式不应该在第一个“3”处中断吗,因为它是所有字符之后的第一个数字

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CaptureGroups1 {
    public static void main(String args[]) {

        String line = "This order was placed for QT3000! OK?";

        String pattern = "(.*)(\\d+)(.*)";
        Pattern r = Pattern.compile(pattern);

        Matcher m = r.matcher(line);
        int count = m.groupCount();

        System.out.println("Number of capturing groups: " + count + '\n');

        if (m.find()) {
            for (int i = 1; i <= count; i++) {
                System.out.println("Found value(capturint group(" + i + ")): " + m.group(i));
            }
        } else {
            System.out.println("Not Found");
        }
    }
}
import java.util.regex.Matcher;
导入java.util.regex.Pattern;
公共类CaptureGroups1{
公共静态void main(字符串参数[]){
String line=“此订单是为QT3000下的!确定吗?”;
字符串模式=“(.*)(\\d+)(.*)”;
Pattern r=Pattern.compile(Pattern);
匹配器m=r.匹配器(线);
int count=m.groupCount();
System.out.println(“捕获组的数量:“+count+'\n”);
if(m.find()){

对于(int i=1;i如果您想要捕获数字组,可能从
(.*)
中删除括号会对您有所帮助。实际上,您甚至不需要它们:

String pattern = "(\\d+)";

我想这在你看来是错误的。 我怀疑你在找这个

String pattern = "(\\D*)(\\d+)(.*)";
也许你也想检查不情愿的量词


这取决于你想做什么。@SotiriosDelimanolis因为他想捕获多个团队,我认为这是不正确的。发布一段代码,然后说,“这是错误的吗?”不会让你有任何进展。请描述你想要发生的事情,并告诉我们是否有任何错误/意外结果。
我有3头猪。我有5头,但其中2头死了。
?@dystroy你在根据代码推断他想要什么:)。他可能只希望第一组是整个字符串,而其他组是空的。这将是一个愚蠢的要求。抱歉,伙计们,我一直在努力放置输出,但它一直抱怨它没有格式化…我想知道为什么这个模式没有将字符串分解为我所期望的。你甚至如何在这个模式中添加新行放置??它输出:捕获组数:3\n找到值(capturint组(1)):此顺序是针对QT300找到值(capturint组(2)):0找到值(capturint组(3)):!好吗?我的答案是基于OP想要得到数字的假设。有人能详细说明一下模式是如何与给定正则表达式中的字符串相匹配的吗?也许我遗漏了什么。我的正则表达式不会转换为匹配任意数量的字符,后跟1个或多个数字,然后再跟任意数量的字符吗?我实际上不会你根本不需要墨水here@user2130360问题是“任意数量的字符”将消耗所有这些字符digits@user2130360正确。所以我的假设是正确的。但是你遗漏了不情愿的量词。