[英]Regex global match term until delimiter, result without term/delimiter
我的字符串包含(FUDI)消息,以;\\n
分隔。 我嘗試提取所有以特定字符串開頭的消息。
以下正則表達式可找到正確的消息,但仍包括定界符和搜索詞。
var input = 'a b;\n'
+ 'a b c;\n'
+ 'b;\n'
+ 'b c;\n'
+ 'b c d;\n';
function search(input, term){
var regex = new RegExp('(^|;\n)' + term + '([^;\n]?)+', 'g');
return input.match(regex);
}
console.log(search(input, 'a b'));
// current: ["a b", ";↵a b c"]
// wanted1: ["a b", "a b c"]
// wanted2: ["", "c"]
console.log(search(input, 'b'));
// current: [";↵b", ";↵b c", ";↵b c d"]
// wanted1: ["b", "b c", "b c d"]
// wanted2: ["", "c", "c d"]
我是regex初學者,因此非常感謝您的幫助。
編輯:使用/ gm解決通緝1
var input = 'a b;\n'
+ 'a b c;\n'
+ 'b;\n'
+ 'b c;\n'
+ 'b c d;\n';
function search(input, term){
var regex = new RegExp('^' + term + '([^;]*)', 'gm');
return input.match(regex);
}
console.log(search(input, 'a b'));
// current: ["a b", "a b c"]
// wanted2: ["", "c"]
console.log(search(input, 'b'));
// current: ["b", "b c", "b c d"]
// wanted2: ["", "c", "c d"]
要擺脫定界符,應使用.split()
而不是.match()
。
str.split(/;\n/);
使用您的示例:
('a b;\n'
+ 'a b c;\n'
+ 'b;\n'
+ 'b c;\n'
+ 'b c d;\n').split(/;\n/)
// ["a b", "a b c", "b", "b c", "b c d", ""]
然后,要找到匹配項,您必須遍歷拆分結果並進行字符串匹配:
function search(input, term)
{
var inputs = input.split(/;\n/),
res = [], pos;
for (var i = 0, item; item = inputs[i]; ++i) {
pos = item.indexOf(term);
if (pos != -1) {
// term matches the input, add the remainder to the result.
res.push(item.substring(pos + term.length));
}
}
return res;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.