正则表达式获取特定字符串

时间:2017-12-12 09:26:06

标签: java regex

My String就像这样 -
word1("word2").word3( "word4","{{word5}}", "sentence6","","word7"|"word8", word9 )除句子6外,所有其他都是静态词。我想通过匹配其他单词值来提取句子 我正在使用正则表达式,但无法处理{{}}()。 那我该怎么办?

2 个答案:

答案 0 :(得分:0)

https://regex101.com/r/hc1r56/1

import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "\\}\\}\", \"(.*)\",\"\"";
final String string = "word1(\"word2\").word3( \"word4\",\"{{word5}}\", \"sentence6\",\"\",\"word7\"|\"word8\", word9 )";

final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println("Full match: " + matcher.group(0));
    for (int i = 1; i <= matcher.groupCount(); i++) {
        System.out.println("Group " + i + ": " + matcher.group(i));
    }
}

答案 1 :(得分:0)

如果要匹配从开头双引号到结束双引号发生"sentence6"的部分,您可以匹配前面的部分直到开头双引号}}", "然后匹配到下一个双引号并在组([^"]+)中捕获:

}}\", \"([^"]+)

}}\", \" # Match }}", "
(        # Capturing group
  [^"]+  # Match not " one or more times
)        # Close capturing group

在java中使用:

\\}}\\\", \\\"([^\"]+)

Demo Java output