31

我有这行文本,引号的数量可能会改变,例如:

Here just one "comillas"
But I also could have more "mas" values in "comillas" and that "is" the "trick"
I was thinking in a method that return "a" list of "words" that "are" between "comillas"

如何获取引号之间的数据?

结果应该是:

comillas
mas, comillas, 把戏
a, 单词, are, comillas

4

6 回答 6

61

您可以使用正则表达式来找出此类信息。

Pattern p = Pattern.compile("\"([^\"]*)\"");
Matcher m = p.matcher(line);
while (m.find()) {
  System.out.println(m.group(1));
}

此示例假定正在解析的行的语言不支持字符串文字中双引号的转义序列,不包含跨越多个“行”的字符串,或支持其他字符串分隔符,如单引号。

于 2009-09-24T17:51:57.967 回答
19

查看StringUtilsApache commons-lang library - 它有一个substringsBetween方法。

String lineOfText = "if(getip(document.referrer)==\"www.eg.com\" || getip(document.referrer)==\"192.57.42.11\"";

String[] valuesInQuotes = StringUtils.substringsBetween(lineOfText , "\"", "\"");

assertThat(valuesInQuotes[0], is("www.eg.com"));
assertThat(valuesInQuotes[1], is("192.57.42.11"));
于 2009-09-24T17:53:26.827 回答
2
String line = "if(getip(document.referrer)==\"www.eg.com\" || getip(document.referrer)==\"192.57.42.11\"";
StringTokenizer stk = new StringTokenizer(line, "\"");
stk.nextToken();
String egStr = stk.nextToken();
stk.nextToken();
String ipStr = stk.nextToken();
于 2009-09-24T17:50:33.023 回答
1

首先,请注意您应该使用 equals() 而不是 ==。默认情况下,“==”询问它们是否是内存中的同一个实例,在字符串中有时可能是这种情况。使用 myString.equals("...") 您正在比较字符串的值。

至于如何获得引号之间的值,我不确定您的意思。“...”是一个实际的对象。或者你可以这样做:

字符串 webUrl = "www.eg.com";

于 2009-09-24T17:51:52.693 回答
1

如果您要解析整个源文件而不仅仅是一行,则基于函数语法的解析器可能比尝试基于字符串执行此操作更安全。

我猜这些将是您语法中的字符串文字。

于 2009-09-24T17:52:25.270 回答
1

如果要从文件中获取所有出现

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class testReadQuotes {


    public static void main(String args[]) throws IOException{

        Pattern patt = Pattern.compile("\"([^\"]*)\"");
        BufferedReader r = new BufferedReader(new FileReader("src\\files\\myFile.txt"));

        String line;

        while ((line = r.readLine()) != null) {

          Matcher m = patt.matcher(line);

          while (m.find()) {
            System.out.println(m.group(0));
          }

        }

    }

}
于 2017-06-11T20:34:28.703 回答