![](/img/trans.png)
[英]Javascript Regex: Match any non-word character that is not a whitespace character
[英]Javascript Regex Word Boundary with optional non-word character
我希望在字符串中找到關鍵字匹配。 我正在嘗試使用字邊界,但這可能不是該解決方案的最佳情況。 關鍵字可以是任何單詞,並且可以以非單詞字符開頭。 該字符串可以是任何字符串,並且可以在數組中包含所有這三個單詞,但我應該只匹配關鍵字:
['hello', '#hello', '@hello'];
這是我的代碼,其中包括在post 中找到的嘗試:
let userStr = 'why hello there, or should I say #hello there?';
let keyword = '#hello';
let re = new RegExp(`/(#\b${userStr})\b/`);
re.exec(keyword);
/(#?\\b${userStr})\\b/
,但如果字符串確實以#
開頭,它會嘗試匹配##hello
。matchThis
STR可以是任何的在陣列中的3個例子,並且userStr可能包含的幾種變化matchThis
但只有一個將是精確您需要在這里說明 3 件事:
\\b
詞邊界是一個上下文相關的構造,如果您的輸入並不總是只有字母數字,則需要明確的詞邊界用
let userStr = 'why hello there, or should I say #hello there?'; let keyword = '#hello'; let re_pattern = `(?:^|\\\\W)(${keyword.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&')})(?!\\\\w)`; let res = [], m; // To find a single (first) match console.log((m=new RegExp(re_pattern).exec(userStr)) ? m[1] : ""); // To find multiple matches: let rx = new RegExp(re_pattern, "g"); while (m=rx.exec(userStr)) { res.push(m[1]); } console.log(res);
圖案說明
(?:^|\\\\W)
- 匹配字符串開頭或任何非單詞字符的非捕獲字符串(${keyword.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&')})
- 第 1 組:帶有轉義的關鍵字值特殊字符(?!\\\\w)
- 如果當前位置的右側有一個單詞 char ,則匹配失敗的負前瞻。檢查關鍵字是否已經以特殊字符開頭。 如果是,請不要將其包含在正則表達式中。
var re;
if ("#@".indexOf(keyword[0]) == -1) {
re = new RegExp(`[@#]?\b${keyword}\b`);
} else {
re = new RegExp(`\b${keyword}\b`);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.