Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/qt/7.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,我想写一个方法,只返回双引号内字符串中的字符。给定String input=“\”x\“y\”z\”,我想返回“xz” 下面的方法只返回“x”,因为模式匹配器只找到一个匹配项 static String removeCharsNotInQuotes(String text) { StringBuilder builder = new StringBuilder(); String withinQuotesRegex = "\"(.*?)\"";

我想写一个方法,只返回双引号内字符串中的字符。给定
String input=“\”x\“y\”z\”
,我想返回
“xz”

下面的方法只返回
“x”
,因为模式匹配器只找到一个匹配项

  static String removeCharsNotInQuotes(String text) {
        StringBuilder builder = new StringBuilder();

        String withinQuotesRegex = "\"(.*?)\"";

        Pattern pattern = Pattern.compile(withinQuotesRegex);
        Matcher matcher = pattern.matcher(text);
        if (matcher.find()) {
            for (int i = 1; i <= matcher.groupCount(); i++) {
                builder.append(matcher.group(i));
                builder.append(" ");
            }
        }

        return builder.toString().trim();
    }
静态字符串removeCharsNotInQuotes(字符串文本){
StringBuilder=新的StringBuilder();
字符串withinQuotesRegex=“\”(.*?\”;
Pattern=Pattern.compile(withinQuotesRegex);
Matcher Matcher=pattern.Matcher(文本);
if(matcher.find()){

对于(int i=1;i您应该为
匹配器.find()
使用while循环。例如:

while (matcher.find()) {
    builder.append(matcher.group(1));
    builder.append(" ");
}
此外,
matcher.groupCount()
返回正则表达式中的组数,因此仅对多个您没有的组使用它才有意义


调用
group()
的整数参数表示要访问正则表达式中的哪些组,因为您只有一个组,所以始终为
1

使用
while
循环不断查找新的匹配项,直到用完为止:

while (matcher.find()) {
    // you don't need to use a for loop here. You just need group 1
    builder.append(matcher.group(1));
    // given your sample output, you don't seem to want a space between 
    // the stuff in each pair of quotes.
    builder.append(" "); 
}
您似乎对
find
的功能感到困惑。它不会找到所有匹配项并将每个匹配项放入一个组中。它只会将匹配器的状态更改为找到的下一个匹配项。

javadoc of
groupCount()
:“返回此匹配器模式中捕获的组数。”-也就是说,不是您正在搜索的字符串中的组数。。。