java模式匹配不起作用
我想从字符串中获取类名。例如,java模式匹配不起作用,java,regex,Java,Regex,我想从字符串中获取类名。例如,public class hello扩展了jframe。然后我想获取hello作为类名。但是如果字符串是public class hello,我还想获取hello 我写了一个正则表达式,它的工作很好 这是我的正则表达式 (public)*\s*class\s+(\S+)\s+ 预演 如您所见,它可以工作..它捕获类名。(红色->第2组) 但是在java中,m.matches()返回false,因为整个字符串只匹配一部分,而不匹配。因此,根据,我使用了hitEnd
public class hello扩展了jframe
。然后我想获取hello
作为类名。但是如果字符串是public class hello
,我还想获取hello
我写了一个正则表达式,它的工作很好
这是我的正则表达式
(public)*\s*class\s+(\S+)\s+
预演
如您所见,它可以工作..它捕获类名。(红色->第2组)
但是在java中,m.matches()
返回false,因为整个字符串只匹配一部分,而不匹配。因此,根据,我使用了hitEnd()
方法,但它也不起作用??当字符串完全不匹配但部分不匹配时,如何捕获类名
String cstring = "public class hello extends jframe ";
Pattern classPattern = Pattern.compile("(public)*\\s*class\\s+(\\S+)\\s*");
Matcher m = classPattern.matcher(cstring);
m.matches();
if (m.hitEnd()) {
System.out.println("found");
String className = m.group(2);
System.out.println(className);
}
输出为空。请参阅下面代码中的注释和说明:
String cstring = "public class hello extends jframe ";
Pattern classPattern = Pattern.compile(".*?class\\s+(\\S+)\\s*"); // regex was changed a bit
Matcher m = classPattern.matcher(cstring);
//m.matches(); // <-- no need for that
if (m.find()) { // use find() instead of m.hitEnd()
System.out.println("found");
String className = m.group(1);
System.out.println(className);
}
基本上,我从正则表达式中删除了(public)
,并使用了“1”匹配组(如果存在匹配,零是整个表达式)。您的正则表达式也可以使用,但是您必须使用第二个匹配组,因为(public)
将首先出现
除此之外,我删除了不需要的
m.matches()
,并将m.hitEnd()
替换为m.find()
,后者应用于迭代匹配的结果。请参见下面代码中的注释和解释:
String cstring = "public class hello extends jframe ";
Pattern classPattern = Pattern.compile(".*?class\\s+(\\S+)\\s*"); // regex was changed a bit
Matcher m = classPattern.matcher(cstring);
//m.matches(); // <-- no need for that
if (m.find()) { // use find() instead of m.hitEnd()
System.out.println("found");
String className = m.group(1);
System.out.println(className);
}
基本上,我从正则表达式中删除了(public)
,并使用了“1”匹配组(如果存在匹配,零是整个表达式)。您的正则表达式也可以使用,但是您必须使用第二个匹配组,因为(public)
将首先出现
除此之外,我删除了不需要的
m.matches()
,并将m.hitEnd()
替换为m.find()
,它应该用于迭代匹配的结果。您需要调用find()
使引擎在尝试访问它之前找到匹配项
String s = "public class hello extends jframe";
Pattern p = Pattern.compile("public\\s*class\\s+(\\S+)");
Matcher m = p.matcher(s);
if (m.find()) {
System.out.println("found");
String className = m.group(1);
System.out.println(className);
}
您需要调用
find()
使引擎在尝试访问它之前找到匹配项
String s = "public class hello extends jframe";
Pattern p = Pattern.compile("public\\s*class\\s+(\\S+)");
Matcher m = p.matcher(s);
if (m.find()) {
System.out.println("found");
String className = m.group(1);
System.out.println(className);
}
尝试如果(m.find())
结果:
found
hello
此外,您的捕获组(\\S+)
将匹配任何可能导致无效类名的非空白字符。考虑将捕获组更改为<代码>([AZ-ZY$] \W*)以捕获有效的类名。 尝试<代码>(m(查找)())< /代码>
结果:found
hello
此外,您的捕获组
(\\S+)
将匹配任何可能导致无效类名的非空白字符。考虑将捕获组更改为<代码>([AZ-ZY$] \W*)以捕获有效的类名。不应该使用<代码> HITENT/CODE >,因为字符串不完全匹配但部分地与pattern@whiletrue,不,您不应该,我也不应该使用hitEnd
,因为字符串与pattern@whiletrue不,你不应该