My string contains (FUDI) messages delimited by ;\\n
. I try to extract all messages beginning with a certain string.
The following regex finds the correct messages, but still include the delimiter and the search term.
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"]
I am a regex beginner so any help is greatly appreciated.
EDIT: solves wanted1 using /gm
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"]
To get rid of the delimiter, you should use .split()
instead of .match()
.
str.split(/;\n/);
Using your example:
('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", ""]
Then, to find the match, you have to iterate through the split result and do the string matching:
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.