有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何用引号捕获这个组?

    String content = "$.test(\"I am do'in testing\") ";
    Matcher matcher = 
     Pattern.compile("\\$.test.*?(.*?[\"'](.*?)[\"'].*?)").matcher(content);

输出为("I am do',但我需要捕获I am do'in testing。我不确定我在这里错过了什么

类似地,输入可以是“$。测试(\'I am do'in testing\”)输出应该是I am do'in testing


共 (1) 个答案

  1. # 1 楼答案

    \$.test.*?(.*?["'](.*?)["'].*?)
    

    这是你的正则表达式。这个正则表达式在["']和另一个["']之间使用惰性量词。当您的输入为:$.test("I am do'in testing")时,这使得它在"(双引号)和'单引号之间匹配

    因此,它匹配并捕获捕获组#1中的I am do

    另一个问题是$之后没有转义点,这可能会导致匹配任何字符而不是文字点

    您可以使用这个正则表达式来匹配单引号或双引号之间的字符串,用反斜杠跳过转义引号

    \$\.test[^'"]*(?:"([^"\\]*(?:\\.[^"\\]*)*)"|'((?:[^'\\]*(?:\\.[^'\\]*)*))').*
    

    RegEx Demo

    代码:

    final String regex = "\\$\\.test[^'\"]*(?:\"([^\"\\\\]*(?:\\\\.[^\"\\\\]*)*)\"|'((?:[^'\\\\]*(?:\\\\.[^'\\\\]*)*))').*";
    
    final Pattern pattern = Pattern.compile(regex);
    final Matcher matcher = pattern.matcher( input );
    
    while (matcher.find()) {
        System.out.printf("Group-1: %s, Group-2: %s%n", matcher.group(1), matcher.group(2));
    }