![](/img/trans.png)
[英]Any way to match a pattern EITHER preceded OR followed by a certain character?
[英]Match pattern not preceded by character
我想讓我的正則表達式匹配一個模式,前提是它前面沒有字符,在我的例子中是^
(circumflex)。
我的正則表達式: /[^\^]\w+/g
用於測試的文本: Test: ^Anotherword
匹配:“Test”和“Anotherword”,即使后者前面有抑揚符。 我試圖通過在開頭插入[^\^]
來阻止。 所以我不僅試圖不匹配抑揚符,而且試圖不匹配它后面的詞。 不應匹配“Anotherword”。
[^\^]
- 如果重音抑揚符在正則表達式前面,這應該阻止正則表達式匹配。
\w+
- 匹配前面沒有抑揚符的任何單詞。
由於 JavaScript 的限制,我無法使用 lookbehind。
使用([^^\\w]|^)\\w+
(見http://regexr.com/3e85b )
它基本上注入了一個單詞邊界,同時也排除了^。
[^\\w] = \\W\\b\\w
否則[^^]
將匹配'^ T
'
和\\w+
將匹配est
。
如果您在其周圍放置捕獲組,則可以看到它。
如果不嚴格匹配。
(?:\\^\\w+)|(\\w+)
:匹配兩個表達式但不為^Anotherworld
生成組。
(?:\\^\\w+)
:匹配^Kawabanga
但不生成任何組。 (\\w+)
:用於分組的所有其他內容。 我想要^Anotherworld
有一個組只是刪除?:
。
隨着ECMAScript 2018 標准的越來越多的采用,考慮后視方法也很有意義:
const text = "One Test: ^Anotherword"; // Extracing words not preceded with ^: console.log(text.match(/\\b(?<!\\^)\\w+/g)); // => [ "One", "Test" ] // Replacing words not preceded with ^ with some other text: console.log(text.replace(/\\b(?<!\\^)\\w+/g, '<SPAN>$&</SPAN>')); // => <SPAN>One</SPAN> <SPAN>Test</SPAN>: ^Anotherword
\\b(?<!\\^)\\w+
正則表達式匹配一個或多個在左邊沒有字字符(字母、數字或_
)的字字符( \\w+
)(通過字邊界實現, \\b
)左邊沒有^
字符(通過負向后視(?<!\\^)
)。 請注意, ^
是一種特殊的正則表達式元字符,如果想要將其匹配為文字插入符字符,則需要對其進行轉義。
對於較舊的 JavaScript 環境,仍然需要使用一種解決方法:
var text = "One Test: ^Anotherword"; // Extracing words not preceded with ^: var regex = /(?:[^\\w^]|^)(\\w+)/g, result = [], m; while (m = regex.exec(text)) { result.push(m[1]); } console.log(result); // => [ "One", "Test" ] // Replacing words not preceded with ^ with some other text: var regex = /([^\\w^]|^)(\\w+)/g; console.log(text.replace(regex, '$1<SPAN>$2</SPAN>')); // => <SPAN>One</SPAN> <SPAN>Test</SPAN>: ^Anotherword
提取和替換正則表達式在捕獲組的數量上有所不同,因為提取時我們只需要一個組,而替換時我們需要兩個組。 如果您決定使用帶有兩個捕獲組的正則表達式進行提取,則需要收集m[2]
值。
提取模式意味着
(?:[^\\w^]|^)
- 非捕獲組匹配
[^\\w^]
- 除了單詞和^
char 之外的任何字符|
- 或者^
- 字符串的開始(\\w+)
- 第 1 組:一個或多個單詞字符。 你可以使用/(?<!^)\\w+/g
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.