匹配器不包含所有匹配的组

问题描述

我有一个正则表达式,它将匹配如下模式:

  • @Mike Hello Mike,how are you doing today?
  • Hello,I'm Mike.

我的正则表达式如下所示:^(?:@(\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 到控制台?信息的平静在哪里?

解决方法

您没有捕获 const catalogsSlice = createSlice({ name: "catalogs",initialState,reducers: {},extraReducers: { [catalogRequest.fulfilled]: (state,action) => { const { data,catalogName } = action.payload; state[catalogName] = data; } } }); 。使用

@Mike

参见regex proof

说明

Pattern.compile( "^(?:@([\\w-]*))?\\s*(.*)$" )