簡體   English   中英

正則表達式匹配有或沒有捕獲組的字符串

[英]Regex to match string with or without capturing group

我已經嘗試了一段時間,不知道谷歌是什么,但我希望這兩者都能匹配

Someone does something

Someone tries to do something

我認為會起作用的是

/^Someone (tries to)? do(es)? something$/

但這僅與第二個字符串匹配。

它們是單獨的字符串,而不是跨越多行的單個字符串。

利用

/^Someone(?: tries to)? do(?:es)? something$/

證明

解釋

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  Someone                  'Someone'
--------------------------------------------------------------------------------
  (?:                      group, but do not capture (optional
                           (matching the most amount possible)):
--------------------------------------------------------------------------------
     tries to                ' tries to'
--------------------------------------------------------------------------------
  )?                       end of grouping
--------------------------------------------------------------------------------
   do                      ' do'
--------------------------------------------------------------------------------
  (?:                      group, but do not capture (optional
                           (matching the most amount possible)):
--------------------------------------------------------------------------------
    es                       'es'
--------------------------------------------------------------------------------
  )?                       end of grouping
--------------------------------------------------------------------------------
   something               ' something'
--------------------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM