[英]regex precceded by two or more special character
我堅持創建正則表達式,這樣如果單詞以特殊字符開頭或結尾,則每側正則表達式'exec'方法上的多個正則表達式應拋出null。 僅當word的兩邊都用一個方括號“ exec”方法包裝時,才應給出結果。下面是我想出的正則表達式。
如果字符串類似於“(test)”,則只有regex.exec應當具有其他組合的值,例如“((test))”或“((test)”或“(test))”,該值應為null。 下面的代碼不會拋出應為null的值。 請提出建議。
var w1 = "\\(test\\)"; alert(new RegExp('(^|[' + '\\(\\)' + '])(' + w1 + ')(?=[' + '\\(\\)' + ']|$)', 'g').exec("this is ((test))"))
如果您有一個單詞列表並想要過濾它們,則可以執行以下操作。
string.split(' ').filter(function(word) {
return !(/^[!@#$%^&*()]{2,}.+/).test(word) || !(/[!@#$%^&*()]{2,}$).test(word)
});
split()
函數在空格字符處分割字符串,並返回一個單詞數組,然后可以對其進行filter
。
為了保留有效的單詞,我們將測試兩個正則表達式,以查看單詞是否分別以2個或更多特殊字符開頭或結尾。
正則分解
^
-表達式從以下開始
[]
-塊中的單個字符
!@#$%^&*()
-這些是我使用的特殊字符。 用所需的替換它們。
{2,}
-匹配2個或多個前面的字符
.+
-匹配1個或多個任意字符
$
-表達式以以下結尾
要以這種方式使用exec
函數,請執行以下操作
!(/^[!@#$%^&*()]{2,}.+/).exec(string) || !(/[!@#$%^&*()]{2,}$).exec(string)
如果我理解正確,那么您正在尋找任何包含(test)
字符串,在其中的任何地方,對吧?
在這種情況下,您可能需要以下內容:
var regExp = /.*[^)]\(test\)[^)].*/;
alert(regExp.exec("this is ((test))")); // → null
alert(regExp.exec("this is (test))" )); // → null
alert(regExp.exec("this is ((test)" )); // → null
alert(regExp.exec("this is (test) ...")); // → ["this is (test) ..."]
說明:
.* matches any character (except newline) between zero and unlimited times, as many times as possible.
[^)] match a single character but not the literal character )
這樣可以確保在給定的字符串中有您的測試字符串,但是永遠只在每一側都用一個大括號包裹它!
您可以使用以下正則表達式:
(^|[^(])(\(test\))(?!\))
在此處查看regex演示 ,替換為$1<span style="new">$2</span>
。
該正則表達式具有一個替換組(^|[^(])
,它與字符串^
開頭或除(
之外的任何其他字符(^|[^(])
匹配。這種替代方法是一種解決方法,因為JS正則表達式引擎不支持向后查找。
然后, (\\(test\\))
匹配並捕獲(test)
。 請注意,圓括號已轉義。 如果不是,則將它們視為捕獲組定界符。
在(?!\\))
是一個前瞻,使得確保沒有文字)
之后test)
。 JS正則表達式引擎完全支持前瞻。
JS代碼段:
var re = /(^|[^(])(\\(test\\))(?!\\))/gi; var str = 'this is (test)\\nthis is ((test))\\nthis is ((test)\\nthis is (test))\\nthis is ((test\\nthis is test))'; var subst = '$1<span style="new">$2</span>'; var result = str.replace(re, subst); alert(result);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.