2011-09-07 125 views
1

我正试图在Java中使用Regexes解析下列内容。Java正则表达式

我的测试字符串由内"${}"如字符串为前:"Test ${template} in ${xyz} : ${abc}"

我试图使用窗体(\$\{[^\}]+\})的正则表达式来匹配它。当前的正则表达式不匹配测试字符串中的任何内容。

如果我添加(.*?)(\$\{[^\}]+\})(.*?)使其无法理解,那么给我任何我想匹配的东西都是不一致的。

我的正则表达式有什么问题?我如何解决它?

+0

我躲过了$和花括号。 – Sachin

+0

like this“(。*?)(\\ $ \\ {[^ \\}] + \\})(。*?)” – Sachin

+0

您可以显示准备运行的示例代码吗? –

回答

1

您可能需要逃避括号,以及:

[email protected]:/usr/src/clusterFix$ python 
Python 2.6.7 (r267:88850, Jun 13 2011, 22:03:32) 
[GCC 4.6.1 20110608 (prerelease)] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import re 
>>> s = 'Test ${template} in ${xyz} : ${abc}' 
>>> re.compile('\$\{[^}]+\}').findall(s) 
['${template}', '${xyz}', '${abc}'] 
6

很多时候有人问正则表达式的问题,我要求他们至少要考虑Commons Lang StringUtils时间:

String[] names = substringsBetween(theString, "${", "}"); 
+0

不知道这一点,好的提示。 –

4
public static void main(String[] args) throws Exception { 

    String test = "Test ${template} in ${xyz} : ${abc}"; 

    Matcher m = Pattern.compile("\\$\\{[^\\}]+\\}").matcher(test); 

    while (m.find()) 
     System.out.println(m.group()); 
} 

输出:

${template} 
${xyz} 
${abc} 
1
String test = "Test ${template} in ${xyz} : ${abc}"; 
    Pattern p = Pattern.compile("\\$\\{[^}]+\\}"); 
    Matcher matcher = p.matcher(test); 
    while (matcher.find()) { 
     System.out.println(matcher.group()); 
    } 
0
 String ip="Test ${template} in ${xyz}"; 
     Pattern p = Pattern.compile("\\{.*?\\}"); 
     Matcher m =p.matcher(ip); 
     while(m.find()) 
     { 
      System.out.println(m.group()); 
     } 
0

一个斜线是不够的。你需要两个斜线。

试试这个正则表达式:

\\$\\{.+\\} 

它检查与$ {和}周围的文本字符串。这可以滤除空白字符串(${})以及任何未正确关闭的东西。

如果你想盈和后面检查的文本,尽量.+\\$\\{.+\\}.+