我正在尝试正则表达式来获取以下内容
输入 -
{foo}
{bar}
\{notgood}
\{bad}
{nice}
\{bad}
Run Code Online (Sandbox Code Playgroud)
输出 -
foo
bar
nice
Run Code Online (Sandbox Code Playgroud)
我想找到所有字符串开头{但不是\{.我只有五个单词作为输入.
我尝试了一个正则表达式,即"\\{(foo|bar|nice|notgood|bad)"以所有单词开头{.我不知道怎么摆脱\{.我怎样才能做到这一点?
您可以使用负向lookbehind断言来确保{只有\在它之前没有匹配时才匹配:
List<String> matchList = new ArrayList<String>();
Pattern regex = Pattern.compile(
"(?<!\\\\) # Assert no preceding backslash\n" +
"\\{ # Match a {\n" +
"(foo|bar|nice|notgood|bad) # Match a keyword\n" +
"\\} # Match a }",
Pattern.COMMENTS);
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
matchList.add(regexMatcher.group(1));
}
Run Code Online (Sandbox Code Playgroud)
matchList然后将包含["foo", "bar", "nice"].