Reputation: 55
I need to match data within a string in order to parse the data. The format for the data is follows
A*(anything)B*(anything)ABC*(anything)
The keys will always be A, B, ABC or DCE.
I have it working for the keys with the length of one character.
$(function() {
var s = "A*(anything)B*(anything)ABC*(anything)DCE*(anything)";
s.match(/(A|B|ABC|DCE)\*[^*]+(?!\*)/g).forEach(match => {
var [k, v] = match.split('*');
console.log(k + "->" + v);
});
});
However, this is the output (doesn't work with 1+ length keys
A->(anything)
B->(anything)AB
DCE->(anything)
The value is not always (anything) - it is dynamic.
I think the issue is with (?!*)/g
Upvotes: 0
Views: 58
Reputation: 19154
why not using [^\)]
instead of [^*]
var s = "A*(anything)B*(anything)ABC*(anything)DCE*(anything)";
// s.match(/[ABCDE]+\*[^\)]+\)/g).forEach(match =>
// or
s.match(/(A|B|ABC|DCE)\*[^\)]+\)/g).forEach(match => {
var [k, v] = match.split('*');
console.log(k + "->" + v);
});
Upvotes: 0
Reputation: 522254
I managed to get your logic working using a formal regex matcher. The problem with your regex pattern is that you are using a negative lookahead to stop the match. Instead, use a positive lookahead which asserts that we have reached the next (A|B|ABC|DCE)*
or the end of the string.
var s = "A*(anything)B*(anything)ABC*(anything)DCE*(anything)";
var regexp = /(A|B|ABC|DCE)\*(.*?)(?=(?:A|B|ABC|DCE)\*|$)/g;
var match = regexp.exec(s);
while (match != null) {
print(match[0].split("\*")[0] + "->"+ match[0].split("\*")[1]);
match = myRegexp.exec(myString);
}
Upvotes: 1