java - Find index of first element of last group regex? -
java - Find index of first element of last group regex? -
i have next problem: have collection of strings kinda this:
"01100110011" "11100110010" "10001110000"
could there written regex finds index of first 1 in lastly grouping of ones? using hashmaps , lots of calculations related lastindexof indexof etc. @ point it's starting ridiculous.
it quite simple, compile next regex , search first match matcher.find()
:
".*(?<!1)(1)"
you can index calling .start(1)
on matcher
object.
the regex finds lastly 1
, not preceded 1 (?<!1)
, finds first 1 in lastly grouping of consecutive 1's.
sample code:
int startingindexoflastgroup(string str) { pattern p = pattern.compile(".*(?<!1)(1)"); matcher m = p.matcher(str); if (m.find()) { homecoming m.start(1); } // homecoming -1 string without 1 homecoming -1; }
the regex above simple, not nice, since backtracks quite bit. if don't want much backtracking, can utilize next regex:
"(?:[^1]*+(1+))*+"
simply put, search 0 or more of non-1 characters [^1]*+
, followed 1 or more of 1
's (1+)
, , such sequence repeated many times possible. since repeated capturing grouping stores index of lastly capture, effective record start index of lastly grouping of consecutive 1
's.
java regex string regex-lookarounds
Comments
Post a Comment