java Java正则表达式和转义元字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5768480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java regular expression and escaping meta characters
提问by Rajanikanth
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
我正在尝试编写正则表达式来匹配嵌入在两个大括号之间的标记。例如,如果 buffer Hello {World}
,我想从字符串中获取“世界”标记。当我使用像\{*\}
Eclipse这样的正则表达式时,会显示一条错误消息
Invalid escape sequence (valid ones are
\b \t \n \f \r \" \' \\
)
转义序列无效(有效的是
\b \t \n \f \r \" \' \\
)
Can anyone please help me? I am new to using regular expressions.
谁能帮帮我吗?我是使用正则表达式的新手。
采纳答案by turingtest37
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.
您应该能够通过使用{(\w*)}
. 括号 () 围绕由 捕获的零个或多个单词字符形成一个捕获组\w*
。如果字符串匹配,则通过调用 Matcher 类上的 group() 方法从捕获组中提取实际标记。
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.
请注意,token 可能是一个空字符串,因为正则表达式 {\w*}" 将匹配 "{}"。如果您想匹配至少一个标记字符,请改用 {\w+}。
回答by anubhava
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));
}
回答by AabinGunz
try this \\{[\\w]*\\}
in java use double \ for escape characters
\\{[\\w]*\\}
在java中试试这个使用双\作为转义字符
回答by chaitanya
You need to escape the {} in the Regex. Just to extract everything between braces, the regex is
您需要转义正则表达式中的 {}。只是为了提取大括号之间的所有内容,正则表达式是
\{.\}