Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex that only matches on odd/even indices

Is there a regex that matches a string only when it starts on an odd or an even index? My use case is a hex string in which I want to replace certain "bytes".

Now, when trying to match 20 (space), 20 in "7209" would be matched as well even though it consists of the bytes 72 and 09. I am restricted to the regex implementation of Notepad++ in this case, so I'm not able to check the match index as e.g. in Java.

My sample input looks like:

324F8D8A20561205231920

I set up a testing page here, the regex should only match the first and the last occurence of 20, since the one in the middle starts on an odd index.

like image 574
RikuXan Avatar asked Sep 10 '25 01:09

RikuXan


2 Answers

You can use the following regex to match 20 at even positions inside a hex string:

20(?=(?:[\da-fA-F]{2})*$)

See demo

I assume the string has no spaces in this case.

In case you have spaces between the values (or any other symbols), this could be an alternative (with $1XX-like replacement string):

((?:.{2})*?)20

See another demo

like image 193
Wiktor Stribiżew Avatar answered Sep 13 '25 06:09

Wiktor Stribiżew


This seems to work for evens:

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

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

grepl(rx,strings) # [1] FALSE  TRUE  TRUE
like image 21
C8H10N4O2 Avatar answered Sep 13 '25 07:09

C8H10N4O2