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 ofgroupCount()
:“返回此匹配器模式中捕获的组数。”-也就是说,不是您正在搜索的字符串中的组数。。。