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

ato*_*fat 24 java quotes tokenize

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

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"
Run Code Online (Sandbox Code Playgroud)

我如何获得结果应该是引号之间的数据?:

comillas
mas,comillas,trick
a,words,are,comillas

eri*_*son 49

您可以使用正则表达式来捕获此类信息.

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

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

  • @ user1071840括号括号`()`使其成为*capture*组:匹配的内容可以在以后引用.方括号`[]`定义一个字符类:里面的任何字符都将被匹配---但是`^`否定了类:除了*列出的那些字符*将被匹配.`\``是一个双引号,因为双引号是Java字符串文字分隔符."*"表示匹配前面的模式的零个或多个,占有率.所以,所有在一起,`([^ \" ]*)`表示"匹配零或多个除双引号之外的任何字符,并将它们记住为一组." (2认同)

Sin*_*hot 15

查看StringUtilsApache commons-lang库 - 它有一个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"));
Run Code Online (Sandbox Code Playgroud)