[英]Javascript regex to get substring, excluding a pattern?
我仍然是初學者:)
我需要得到一個忽略[]
最后一部分(包括方括號[])的子字符串,即忽略最后的[something inside]
部分。
注意-字符串中可能還存在[
其他單個事件。 並且它們應該出現在結果中。
例
輸入表格-
1 checked arranged [1678]
所需的輸出-
1 checked arranged
我嘗試了這個
var item = "1 checked arranged [1678]";
var parsed = item.match(/([a-zA-Z0-9\s]+)([(\[d+\])]+)$/);
|<-section 1 ->|<-section 2->|
alert(parsed);
我試圖表達以下意思-
第1節 -多次出現單詞(包含文字和數字),后跟空格
第2節 -最終忽略模式。
但是我得到的是1678],1678,]
,但我不確定它的發展方向。
謝謝
好的,這是您的表情問題
([a-zA-Z0-9\s]+)([(\[d+\])]+)$
問題僅在最后一部分
([(\[d+\])]+)$
^ ^
here are you creating a character class,
what you don't want because everything inside will be matched literally.
((\[d+\])+)$
^ ^^
here you create a capturing group and repeat this at least once ==> not needed
(\[d+\])$
^
here you want to match digits but forgot to escape
那把我們帶到
([a-zA-Z0-9\s]+)(\[\d+\])$
在Regexr上看到它,完整的字符串匹配,捕獲組1中的第1部分和組2中的第2部分。
現在,將整個內容替換為第1組的內容時,您就完成了。
你可以這樣做
var s = "1 checked arranged [1678]";
var a = s.indexOf('[');
var b = s.substring(0,a);
alert(b);
http://jsfiddle.net/jasongennaro/ZQe6Y/1/
這個s.indexOf('[');
檢查第一個[
在字符串中出現的位置。
這個s.substring(0,a);
從開始到第一個[
切掉字符串。
當然,這假設字符串始終采用相似的格式
var item = '1 check arranged [1678]',
matches = item.match(/(.*)(?=\[\d+\])/));
alert(matches[1]);
我使用的正則表達式利用正向查找來排除字符串中不需要的部分。 括號中的數字必須是字符串的一部分,才能成功進行匹配,但不會在結果中返回該數字。
在這里,您可以找到如何刪除方括號內的內容。 這將使您剩下的一切。 :)正則表達式:刪除方括號中的內容
如果最終只想擺脫該[],請嘗試此操作
var parsed = item.replace(/\s*\[[^\]]*\]$/,"")
var item = "1 checked arranged [1678]";
var parsed = item.replace(/\s\[.*/,"");
alert(parsed);
想要的工作?
使用轉義括號和不包含括號的括號:
var item = "1 checked arranged [1678]";
var parsed = item.match(/([\w\s]+)(?:\s+\[\d+\])$/);
alert(parsed[1]); //"1 checked arranged"
正則表達式的說明:
([\w\s]+) //Match alphanumeric characters and spaces
(?: //Start of non-capturing parentheses
\s* //Match leading whitespace if present, and remove it
\[ //Bracket literal
\d+ //One or more digits
\] //Bracket literal
) //End of non-capturing parentheses
$ //End of string
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.