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