Java正则表达式和转义元字符 [英] Java regular expression and escaping meta characters

查看:269
本文介绍了Java正则表达式和转义元字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写regexp来匹配嵌入在两个花括号之间的标记。例如,如果缓冲区 Hello {World} ,我想从String中获取World标记。当我使用regexp如 \ {* \} eclipse显示错误消息为

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


无效的转义序列(有效转义序列为 \b \t \ n \f \ r \\'\\

任何人都可以帮助我吗?我是新手使用正则表达式。

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

推荐答案

您应该能够使用 {(\ w *)}的正则表达式从字符串中提取令牌,例如{token}
括号()形成一个捕获组,围绕由 \ w * 捕获的零个或多个单词字符。
如果字符串匹配,通过调用Matcher类上的group()方法从捕获组中提取实际令牌。

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();
}

请注意,令牌可能是空字符串,因为正则表达式{\w *}将匹配{}。如果要匹配至少一个标记字符,请改用{\w +}。

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.

这篇关于Java正则表达式和转义元字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆