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.

+3


source to share


3 answers


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

+4


source


This seems to work:



rx <- "^(.{2})*(20)"

strings <- c("7209","2079","9720")

grepl(rx,strings) # [1] FALSE  TRUE  TRUE

      

+1


source


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

      

+1


source







All Articles