Reputation: 231
I have wrote the following code:
var RegExpression = new RegExp ("!?[a-z][&|]!?[a-z]", "g");
document.addEventListener("DOMContentLoaded", function() {
submit.addEventListener("click", function() {
alert(document.getElementById ("expression")
.value.match(RegExpression).join(", "));
});
});
<input type="text" id="expression">
<input type="button" id="submit" value="Submit!">
I want to get from this code the following:
Example input: !a&b|c&!d&e|f
Output: !a&b, b|c, c&!d, d&e, e|f
, but I get:
Output: !a&b, c&!d, e|f
How to fix it?
If anything, I'm sorry for my English.
Upvotes: 0
Views: 317
Reputation: 600
(?=(!?[a-z][&|]!?[a-z])).
A matching group inside a positive look ahead can be used to match overlapping groups. The dot in the end is just used to proceed.
The output would be:
!a&b, a&b, b|c, c&!d, !d&e, d&e, e|f
which is more than you wanted, but if you want solve this with plain regex this should be close.
Upvotes: 0
Reputation:
I don't know if it can be done directly with a regex or not, but one thing you can do is use the .exec()
method of the regex object in a loop instead.
Because your regex is g
global, the regex object maintains the state of the ending point of the last match. This is stored at the .lastIndex
property of the regex object and is mutable, so you can simply decrement it one position before doing the next call.
var re = /!?[a-z][&|]!?[a-z]/g;
var input = "!a&b|c&!d&e|f";
var match = null;
var result = [];
while ((match = re.exec(input))) {
result.push(match); // Add the match to our result Array
re.lastIndex -= 1; // Start the next call on the last char of the last match
}
console.log(result.join("\n\n"));
Upvotes: 2
Reputation: 1865
I think this should work for you:
const input = document.createElement('input')
const result = document.createElement('div')
input.value = `!a&b|c&!d&e|f`
const split = data => {
const result = data.replace(/(!?\w+)/g, '$1,$1').replace(/.*?,/, '')
return result.substr(0, result.lastIndexOf(',')).split(',')
}
input.addEventListener('keyup', () => {
result.innerText = split(input.value).join(', ')
})
document.body.appendChild(input)
document.body.appendChild(result)
Upvotes: 0