【发布时间】:2021-07-09 23:45:57
【问题描述】:
我有一个正则表达式,它将匹配如下模式:
@Mike Hello Mike, how are you doing today?Hello, I'm Mike.
我的 RegEx 如下所示:^(?:@(\w|-|_|)*)?\s*(.*)$
但是在我的代码中,Matcher 不知何故只能识别Hello Mike ......。 @Mike 无法识别。
代码:
public static void main(String[] args) {
String withAt = "@Mike Hello Mike, how are you doing today?";
String withoutAt = "Hello, I'm Mike.";
matchString(withAt);
matchString(withoutAt);
}
private static void matchString(String messageString) {
System.out.println("Maching String: " + messageString);
Pattern messagePattern = Pattern.compile( "^(?:@(\\w|-|_|)*)?\\s*(.*)$" );
Matcher matcher = messagePattern.matcher(messageString);
if (matcher.find()) {
System.out.println("@: " + matcher.group(1));
System.out.println("Message: " + matcher.group(2));
}
}
运行这种和平的代码将产生以下输出:
Maching String: @Mike Hello Mike, how are you doing today?
@:
Message: Hello Mike, how are you doing today?
Maching String: Hello, I'm Mike.
@: null
Message: Hello, I'm Mike.
问题:
为什么withAt-String 不将@: Mike 打印到控制台?这种信息的平静在哪里?
【问题讨论】:
-
试试:
^(?:@([\\w-]+))?\\s*(.*)$
标签: java regex pattern-matching