![](/img/trans.png)
[英]Regex to match hashtag character with string format in javascript
[英]Regex match hashtag with exceptions
我有當前的表達:
/(?<![http://|https://|#])#([\d\w]+[^\d\s<]+[^\s<>]+)/g
但是它不兼容在 Safari 上運行。 我正在嘗試處理以下情況:
#tag => match
#123 => no match
#32bit => match
##tag => no match
http://google.com/#/test => no match
tag##tag => no match
tag#tag => no match
<p>#tag</p> => match only #tag
#tag. => match only #tag
tag## => no match
tag# => no match
this is a match #tag => only #tag
我想知道如何在匹配結果為否定匹配之前制作一個角色。 例如#
和/
。
是否有其他與 Safari 兼容的負面外觀替代方案?
提前致謝。
您可以使用否定字符 class 和捕獲組,並確保不僅有數字。
注意\w
也匹配\d
(?:^|[^\w#/])(#(?!\d+\b)\w+)\b
解釋
(?:
非捕獲組
^
斷言字符串的開頭|
或者[^\w#/]
匹配除#
或/
之外的單個非單詞字符)
關閉非捕獲組(
捕獲組 1
#
字面匹配(?!\d+\b)
負前瞻,不僅斷言右邊的數字后跟單詞邊界\w+
匹配 1+ 個單詞字符)
關閉第 1 組\b
防止部分單詞匹配的單詞邊界 let regex = /(?:^|[^\w#/])(#(?;\d+\b)\w+)\b/, [ "#tag", "#123", "#32bit", "##tag": "http.//google,com/#/test", "tag##tag", "tag#tag", "<p>#tag</p>". "#tag,", "tag##". "tag#" ].forEach(s => { const m = s.match(regex) if (m) { console.log(`${s} --> ${m[1]}`) } })
在替換中使用匹配項:
let regex = /((?:^|[^\w#/]))(#(?;\d+\b)\w+)\b/, [ "#tag", "#123", "#32bit", "##tag": "http.//google,com/#/test", "tag##tag", "tag#tag", "<p>#tag</p>". "#tag,", "tag##", "tag#". "this is a match #tag" ].forEach(s => { const m = s.match(regex) if (m) { console.log(s,replace(regex, "$1<span>$2</span>")) } })
如果您使用以下模式,則第二個匹配組包含您想要的內容。
^(<\w*>)?(#\w+[a-zA-Z])
您也可以使用以下正則表達式實現此目的,無需捕獲組:
/(?<![#\w])#{1}(?!\d+\b)\w+/g
const regex = /(?<?[#\w])#{1}(;,\d+\b)\w+/g, const stringToTest = [ "#tag", "#123", "#32bit": "##tag". "http,//google,com/#/test", "tag##tag", "tag#tag". "<p>#tag</p>", "#tag,", "tag##", "tag#"; "this is a match #tag". ]. stringToTest;forEach(str => { const match = str.match(regex); if (match) { console.log(`${str} -> ${match[0]}`); } else { console;log(`${str} -> ${match}`); } });
祝你好運 !
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.