I'm struggling to work with regular expressions. I think I understand the individual expressions but combining something together has me completely stumped. I don't grasp the use of something equivalent to an AND operator to connect the pieces I want together into a "full" match expression.
For example, I'd like to split a string into an array breaking on any values of <1>
to <57>
and </1>
to </57>
.
So, I thought I needed something like:
( '<' or '<\/' ) and ( [1-9] or [1-4][0-9] or [5][0-7] ) and '>'
I can get separately <[1-4][0-9]> to work or </[1-4][0-9]>, but when combined together with a '|' it returns partial matches or undefined in between full matches.
Could you please tell me what I am not understanding? Attached is my example.
If click 'Try' for the first expression, it produces empty values after each <21>
or </21>
. This prints as undefined in the console.log when I test it. The second expression produces <
and </
after each tag. I don't understand this, let alone how to get the fuller expression earlier in this question converted into a regExp.
The desired output is:
'This is a', '<21>', 'test', '<\/21>', '.'
Thank you.
ADDITION
After receiving Georg's answer to this question, I became interested in finding a method of escaping these tags, especially since there is not currently supported a negative look-back except in Chrome only. By that I mean \<21>
would be treated as regular text and not generate a split of the string at that point. If you are interested in something similar, you may likely find the answer to my follow-up question provided by Revo here quite helpful.
let b, B = document.querySelectorAll('button');
for ( b of B ) b.addEventListener( 'click', split_str, false );
function split_str( evt )
{
let e = evt.currentTarget,
r = new RegExp( e.previousElementSibling.value ),
s = e.parentNode.previousElementSibling.value;
e.parentNode.lastElementChild.textContent = s.split(r);
}
div > div { border: 1px solid rgb(150,150,150); width: 500px; height: 200px;padding: 5px; }
input { border: 1px solid rgb(150,150,150); width: 500px; margin-bottom: 20px; padding:5px; }
<input type='text' value="This is a<21>test</21>.">
<div>
<input type='text' value="(<[1-4][0-9]>)|(<\/[1-4][0-9]>)"> <button>try</button>
<input type='text' value="((<|<\/)[1-4][0-9]>)"> <button>try</button>
<div></div>
</div>