2012-03-05 120 views
2

对于字符串值"ABCD_12"(包括引号),我想只提取的内容和排除了双引号,即ABCD_12。我的代码是:正则表达式 - Java的

private static void checkRegex() 
{ 
    final Pattern stringPattern = Pattern.compile("\"([a-zA-Z_0-9])+\""); 
    Matcher findMatches = stringPattern.matcher("\"ABC_12\""); 
    if (findMatches.matches()) 
     System.out.println("Match found" + findMatches.group(0)); 
} 

现在,我已经尝试过做findMatches.group(1);,但只返回最后一个字符字符串中(我不明白为什么!)。

我该如何提取只留下双引号的内容?

+0

请尝试提供具体标题问题 - 这个基本标题有几十个问题 – DNA 2012-03-05 22:24:07

回答

6

试试这个正则表达式:

Pattern.compile("\"([a-zA-Z_0-9]+)\""); 

OR

Pattern.compile("\"([^\"]+)\""); 

问题在你的代码是放错地方+外右括号。 这是导致捕获组只捕获1个字符(因为+在外面),这就是为什么最终只能得到最后一个字符的原因。

+0

知道了!谢谢anubhava – 2012-03-05 21:51:18

+0

不客气。 – anubhava 2012-03-05 21:53:17

1

一个不错的简单(读:非正则表达式)的方式来做到这一点是:

String myString = "\"ABC_12\""; 
String myFilteredString = myString.replaceAll("\"", ""); 
System.out.println(myFilteredString); 

让你

ABC_12 
1

您应该将模式改成这样:

final Pattern stringPattern = Pattern.compile("\"([a-zA-Z_0-9]+)\"");

请注意,+标志已移到组内,因为您wa nt字符重复成为该组的一部分。在你发布的代码中,你实际搜索的是该组的重复,其中包括在[a-zA-Z_0-9]中单个字符的单次发生。

1

如果你的模式是严格的在双引号之间的任何文本,那么你可以使用子会更好:

String str = "\"ABC_12\""; 
System.out.println(str.substring(1, str.lastIndexOf('\"'))); 

假设这是一个比较复杂的(在一个更大的字符串之间双引号),你可以使用分裂()函数模式类和使用\“作为你的正则表达式 - 这将拆分字符串围绕\”这样你就可以很容易地提取内容你想

Pattern p = Pattern.compile("\""); 
    // Split input with the pattern 
    String[] result = 
      p.split(str); 
    for (int i=0; i<result.length; i++) 
     System.out.println(result[i]); 
    } 

http://docs.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html#split%28java.lang.CharSequence%29