簡體   English   中英

正則表達式用哈希標記捕獲括號?

[英]Regex to capture parenthesis with hash tag?

到目前為止,我有這個完美的正則表達式:

(?:(?<=\s)|^)#(\w*[A-Za-z_]+\w*)

它找到以哈希標記開頭的任何單詞(例如#lolz但不是hsshs #jdjd)

問題是我也希望它匹配括號。 所以,如果我有這個,它將匹配:

(#lolz哇)

或者(哇#cool)

(#cool)

關於我如何制作或使用我的正則表達式這樣工作的任何想法?

以下似乎對我有用......

\(?#(\w*[A-Za-z_]+\w*)\)?

你在上下文中使用以下方式的方式是矯枉過正的..

\w*[A-Za-z_]\w*

\\w單獨匹配單詞字符( azAZ0-9_ )。 並且沒有必要使用非捕獲組(?:在這里包圍你的lookbehind斷言。

我相信以下就足夠了。

(?<=^|\s)\(?#(\w+)\)?

正則表達式:

(?<=         look behind to see if there is:
 ^           the beginning of the string
 |           OR
  \s         whitespace (\n, \r, \t, \f, and " ") 
)            end of look-behind
\(?          '(' (optional (matching the most amount possible))
 #           '#'
  (          group and capture to \1:
   \w+       word characters (a-z, A-Z, 0-9, _) (1 or more times)
  )          end of \1
 \)?         ')' (optional (matching the most amount possible))

查看live demo

如果你願意,你也可以在這里使用負面的lookbehind。

(?<![^\s])\(?#(\w+)\)?

暫無
暫無

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

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