Regex that only matches odd / even indices
Is there a regex that only matches a string when it starts at an odd or even index? My use case is a hex string where I want to replace specific "bytes".
Now when trying to match 20
(space), 20
"7209" will also match, even if it consists of bytes 72
and 09
. In this case I am limited to the Regex Notepad ++ implementation, so I cannot check the match index, eg. in Java.
My example input looks like this:
324F8D8A20561205231920
I set up the testing page here , the regex should only match the first and last occurrence 20
, since the value in the middle starts at an odd index.
source to share
You can use the following regex to match 20
at even positions within a hex string:
20(?=(?:[\da-fA-F]{2})*$)
Watch the demo
My guess is that the string has no spaces in this case.
If you have spaces between values ββ(or any other characters), this might be an alternative (with string replacement $1XX
):
((?:.{2})*?)20
See another demo
source to share
Don't know what Notepad ++ uses for the regex engine - it's been a while since I've been using it. This works in javascript ...
/^(?:..)*?(20)/
...
/^ # start regex
(?: # non capturing group
.. # any character (two times)
)*? # close group, and repeat zero or more times, un-greedily
(20) # capture `20` in group
/ # end regex
source to share