如何使用正则表达式拆分特定行

时间:2016-08-09 09:08:42

标签: java regex string

我有以下字符串:

"body":"The Example 1",(sample),{sample},"sample",&sample,"body":"The Example 2",(sample),{sample},"sample",&sample

从上面的字符串中,我需要提取

  • "The Example 1"变量string1
  • "The Example 2"变量string2

我使用以下代码

 Pattern comment1 = Pattern.compile("(?<=\")(?:\\\\.|([\"body\"]))*(?=\")", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.DOTALL | Pattern.MULTILINE);
 Matcher matchComm = comment1.matcher(responce.toString());

我没有得到正确的结果。

2 个答案:

答案 0 :(得分:3)

这样可以解决问题:

(?<=:")((?=",|"$)|.)+
  • (?<=:"):"背后隐藏的外观。
  • (?=",|"$)","$的预示,其中$标记了行/文件的结尾。

演示:https://regex101.com/r/qT4oO6/2

EDIT1:

以下代码可用于生成数组,其中数组中的每个位置都与输入字符串分开匹配。

String input = PUT YOUR STRING HERE!;
String pattern = "(?<=:\")((?=",|\"$)|.)+";
ArrayList<String> out = new ArrayList<String>();
Pattern p = Pattern.compile(pattern, Pattern.MULTILINE);
Matcher m = p.matcher(input);

while(m.find()){
  out.add(m.group());
}

<强> EDIT2:

因为你在写完问题后明确表示你确实只想在&#34; body&#34;之后加工字符串。标签,将需要以下正则表达式:

(?<="body":")((?=",|"$)|.)+

此外,如果&#34;身体&#34;之后的字段标记允许为空,+应该换成*

(?<="body":")((?=",|"$)|.)*

答案 1 :(得分:1)

我认为你可以做一个更好的正则表达式(不需要lookbehinds / lookaheads)。添加(?i)以使其不区分大小写。

public static void main(String[] args) {
    String s = "\"body\":\"The Example 1\",\"body\":\"The Example 2\"";
    Pattern p = Pattern.compile("\"body\":\"(.*?)\""); // Capture everything after "body"
    Matcher m = p.matcher(s);
    while(m.find()) {
        System.out.println(m.group(1));
    }
}

O / P:

The Example 1
The Example 2