-2

I am trying to solve this simple HackerRank problem with regex (w/ Javascript):

https://www.hackerrank.com/challenges/alternating-characters/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=strings

To learn more about regular expressions, I want to build a regex out of my own logic so I have refused to look at the discussions, however after some turmoil in trying to make what I thought was a simple regex I have decided to ask here.

What I want to do is make a Regex that finds all pairs of consecutive alphanumeric characters, so for the string "AAAA" should match ["AA", "AA", "AA"] for the first and second As, the second and third As, and the third and fourth As, respectively. If my thinking is correct, this will count the number of adjacent repeated characters in a string.

The closest I came was

/(\w)\1{1}/g

which comes close, but seems to skip all characters it has already scanned, so it misses the "AA" comprised of the second and third As above, since it has already counted the second A in the first pair of As (I think).

Is such a regex possible?

EDIT: Thanks! Lookahead was the answer and I didn't know about that before as I am new to regex so this was good. My full function for the solution is

function alternatingCharacters(s) {
    return s.match(/(\w)(?=\1)/g) != null ? s.match(/(\w)(?=\1)/g).length : 0; 
}
decisions
  • 5
  • 4

1 Answers1

0

Lookahead has to be used as it would not consume any character. In Python,

str1 = "hello he is good aaaaa"
# findall returns just capturing groups so there has to be outer capturing group too
[groups[0]+groups[1] for groups in re.findall(r'((\w)(?=\2))', str1)] 

['ll', 'oo', 'aa', 'aa', 'aa', 'aa']
ggaurav
  • 1,764
  • 1
  • 10
  • 10