Rajanikanth
Rajanikanth

Reputation: 33

Java regular expression and escaping meta characters

I am trying to write regexp for matching token embedded between two curly braces. For example if buffer Hello {World}, I want to get "World" token out of String. When I use regexp like \{*\} eclipse shows a error messages as

Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \\)

Can anyone please help me? I am new to using regular expressions.

Upvotes: 3

Views: 13675

Answers (4)

anubhava
anubhava

Reputation: 785196

Use this code to match string between { and }

String str = "if buffer Hello {World}";
Pattern pt = Pattern.compile("\\{([^}]*)\\}");
Matcher m = pt.matcher(str);
if (m.find()) {
    System.out.println(m.group(0));
}

Upvotes: 5

turingtest37
turingtest37

Reputation: 74

You should be able to extract the token from a string such as "{token}" by using a regexp of {(\w*)}. The parentheses () form a capturing group around the zero or more word characters captured by \w*. If the string matches, extract the actual token from the capturing group by calling the group() method on the Matcher class.

Pattern p = Pattern.compile("\\{(\\w*)\\}");

Matcher m = p.matcher("{some_interesting_token}");

String token = null;
if (m.matches()) {
 token = m.group();
}

Note that token may be an empty string because regex {\w*}" will match "{}". If you want to match on at least one token characters, use {\w+} instead.

Upvotes: 3

chaitanya
chaitanya

Reputation: 1601

You need to escape the {} in the Regex. Just to extract everything between braces, the regex is

\\{.\\}

Upvotes: 0

AabinGunz
AabinGunz

Reputation: 12347

try this \\{[\\w]*\\} in java use double \ for escape characters

Upvotes: 1

Related Questions