Vikas Khengare
Vikas Khengare

Reputation: 124

Regular expression to filter out "\{" but allow "{"

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?

Upvotes: 1

Views: 88

Answers (2)

jJ'
jJ'

Reputation: 3078

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}

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336378

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"].

Upvotes: 5

Related Questions