正则表达式-Java

正则表达式-Java,java,regex,Java,Regex,对于字符串值“ABCD_12”(包括引号),我只想提取内容并排除双引号,即ABCD_12。我的代码是: private static void checkRegex() { final Pattern stringPattern = Pattern.compile("\"([a-zA-Z_0-9])+\""); Matcher findMatches = stringPattern.matcher("\"ABC_12\""); if (findMatches.matche

对于字符串值
“ABCD_12”
(包括引号),我只想提取内容并排除双引号,即
ABCD_12
。我的代码是:

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),但这只返回字符串中的最后一个字符(我不明白为什么!)

如何只提取不带双引号的内容?

试试这个正则表达式:

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

代码中的问题是右括号外的
+
放错了位置导致捕获组只捕获1个字符(因为
+
在外部),这就是为什么最终只获取最后一个字符。

一种简单的方法(读取:非正则表达式)是:

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

ABC_12

您应该将模式更改为:

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


请注意,
+
符号已在组内移动,因为您希望字符重复成为组的一部分。在您发布的代码中,您实际搜索的是组的重复,这包括在
[a-zA-Z_0-9]
中出现单个字符,如果您的模式严格来说是双引号之间的任何文本,那么您最好使用子字符串:

String str = "\"ABC_12\"";
System.out.println(str.substring(1, str.lastIndexOf('\"')));
假设它有点复杂(在较大的字符串之间使用双引号),您可以在Pattern类中使用split()函数,并使用\“作为正则表达式-这将围绕\”拆分字符串,以便轻松提取所需的内容

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]);
    }
Pattern p=Pattern.compile(“\”);
//使用模式分割输入
字符串[]结果=
p、 分裂(str);

对于(int i=0;i请尝试给出问题的具体标题-有几十个问题都有这个基本标题
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]);
    }