an equal value subarray subarray containing 1 or more consecutive elements of same value.
for example, lets our array is:
1,1,3
there 4 equal value sub-arrays:
[1], [1], [3], [1,1]
note elements can part of more 1 subarray.
i know [\d]
matches digits, requirement failing me. asking regex solution out of curiosity.
there's no way 1 regex. in fact, recommend use more 1 version of string.
this regex should work:
^(\d+)(,\1){n}
i've made adjustments ensure more robust regex:
- allows numbers greater 10
- will match @ start, ensuring count not thrown off
for array of length 4, should replace n
0
, 1
, 2
, 3
. means have match against 4 regexes.
(note n=0
same ^(\d+)
)
furthermore, have "behead" string, meaning first match against 1,1,1,3
(new example) , 1,1,3
, , 1,3
, , 3
.
fun fact: can use regex behead string (group 1 have beheaded string):
^\d+,(.*)
(obviously, need ensure you're not trying behead array of size 1.)
for array of size 4, need match against 4+3+2+1=10 regexes. should test see if regex matched; if did, know increment count 1. (note 10 maximum number of consecutive combinations array of 4.)
here's explanation of why need use more 1 string. take regex:
(\d)(,?\1){n}
again, n
needs replaced. need use g
modifier (or equivalent).
i'll use example of 1,1,1,1
:
n=0
gives 4 matchesn=1
gives 2 matchesn=2
gives 1 matchn=3
gives 1 match
as can see, not handle overlapping matches well, because that's not how regex designed.
Comments
Post a Comment