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.
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));
}
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.
try this \\{[\\w]*\\}
in java use double \ for escape characters
You need to escape the {} in the Regex. Just to extract everything between braces, the regex is
\\{.\\}
精彩评论