1

I am trying for regular expression to get following thing

Input-

{foo}
{bar}
\{notgood}
\{bad}
{nice}
\{bad}

Output-

foo
bar
nice

I want to find all strings starting with { but NOT with \{. I have only five words as input.

I tried a regular expression i.e. "\\{(foo|bar|nice|notgood|bad)" which gives all words starting with {. I don't know how to get rid of \{. How can I do that?

4

2 回答 2

5

You could use a negative lookbehind assertion to make sure that a { is only matched if no \ precedes it:

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));
} 

matchList will then contain ["foo", "bar", "nice"].

于 2012-05-04T16:31:23.450 回答
0

You can use a 'group-match' string for that, as in the following code:

str.replaceAll("(?<!\\\\)\\{(foo|bar|nice|notgood|bad)\\}", "$1");

the $1 refers to the first () group in the input

for str = "{foo} \{bar} {something}" it will give you foo \{bar} {something}

于 2012-05-04T16:23:11.453 回答