我有一个RegEx,它将匹配如下模式:
@Mike Hello Mike, how are you doing today?
Hello, I'm Mike.
My 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
-字符串不将@: Mike
打印到控制台?这种信息的平静在哪里?
您没有捕获@Mike
。使用
Pattern.compile( "^(?:@([\w-]*))?\s*(.*)$" )
请参阅正则表达式证明。
解释
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
(?: group, but do not capture (optional
(matching the most amount possible)):
--------------------------------------------------------------------------------
@ '@'
--------------------------------------------------------------------------------
( group and capture to 1:
--------------------------------------------------------------------------------
[w-]* any character of: word characters (a-
z, A-Z, 0-9, _), '-' (0 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
) end of 1
--------------------------------------------------------------------------------
)? end of grouping
--------------------------------------------------------------------------------
s* whitespace (n, r, t, f, and " ") (0 or
more times (matching the most amount
possible))
--------------------------------------------------------------------------------
( group and capture to 2:
--------------------------------------------------------------------------------
.* any character except n (0 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
) end of 2
--------------------------------------------------------------------------------
$ before an optional n, and the end of the
string