我正在嘗試使用正則運算式從降價檔案中僅獲取h1和h2標頭,但不幸的是我不太了解正則運算式并且無法撰寫正確的解決方案。
有了這個運算式,我就接近解決方案了(我認為是這樣):
/\#{1,2} (.*?)(\\r\\n|\\r|\\n)/gm
但它也會回傳具有兩個以上哈希值的標頭。
測驗用例:
# first \r
## second \r
### third \r## fourth \r
這應該回傳 ['first', 'second', 'fourth']
uj5u.com熱心網友回復:
用
/(?<!#)#{1,2} (.*?)(\\r(?:\\n)?|\\n)/gm
請參閱正則運算式證明。
解釋
--------------------------------------------------------------------------------
(?<! look behind to see if there is not:
--------------------------------------------------------------------------------
# '#'
--------------------------------------------------------------------------------
) end of look-behind
--------------------------------------------------------------------------------
#{1,2} '#' (between 1 and 2 times (matching the
most amount possible))
--------------------------------------------------------------------------------
' '
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
.*? any character except \n (0 or more times
(matching the least amount possible))
--------------------------------------------------------------------------------
) end of \1
--------------------------------------------------------------------------------
( group and capture to \2:
--------------------------------------------------------------------------------
\\ '\'
--------------------------------------------------------------------------------
r 'r'
--------------------------------------------------------------------------------
(?: group, but do not capture (optional
(matching the most amount possible)):
--------------------------------------------------------------------------------
\\ '\'
--------------------------------------------------------------------------------
n 'n'
--------------------------------------------------------------------------------
)? end of grouping
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
\\ '\'
--------------------------------------------------------------------------------
n 'n'
--------------------------------------------------------------------------------
) end of \2
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/369755.html
標籤:javascript 正则表达式
上一篇:動態更新類的偽元素屬性
