Path: csiph.com!eternal-september.org!feeder.eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail From: Andreas Leitgeb Newsgroups: comp.lang.java.programmer Subject: Re: regex replaceAll? Date: Fri, 2 Mar 2018 20:15:43 -0000 (UTC) Organization: A noiseless patient Spider Lines: 50 Message-ID: References: <4a800440-39fe-4684-8369-e6a4e6b9d79f@googlegroups.com> <44c665e1-e965-4e9b-8aa0-72aa20607e63@googlegroups.com> <8c677118-8115-409d-8d3b-396e54b063ae@googlegroups.com> <5e445e98-76e9-4feb-9955-035a6c5a2ed5@googlegroups.com> <9730d36c-f472-4b7f-9edb-deedc1630868@googlegroups.com> Reply-To: avl@logic.at Injection-Date: Fri, 2 Mar 2018 20:15:43 -0000 (UTC) Injection-Info: reader02.eternal-september.org; posting-host="43ee598cf591b5380ca4fc229b7a3f4b"; logging-data="26469"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+UHn+E4A7o0MXx8hOwIllJ" User-Agent: slrn/1.0.2 (Linux) Cancel-Lock: sha1:Gzp2xNlMnZso4Z39pjny7wyaiKY= Xref: csiph.com comp.lang.java.programmer:38110 Eric Douglas wrote: > Nope, see what I mean? Apparently not intuitive. > out = in.replaceAll("(?<=\\G[^b]*b[^b]*)b", "_"); > still getting output exactly the same as the input. It really seems to me now as if Java (1.8.0_131 here) was just buggy here: "abaabaaabaaaabaaaaabaaaaaabxbb".replaceAll( "(?<=\G[^b]*b[^b]*b[^b]*)b", "_"); works, while "abaabaaabaaaabaaaaabaaaaaabxbb".replaceAll( "(?<=\G[^b]*b[^b]*)b", "_"); doesn't. The apparent "pattern" is, that adding "b[^b]*" will alternate between working and not working. Using {2} in a (?<=...) doesn't seem to work at all -- "Look-behind group does not have an obvious maximum length ..." Anyway: out = in.replaceAll( "([^b]*b[^b]*)[b]" , "$1_"); seems to work just fine, and: out = in.replaceAll( "([^b]*(b[^b]*){2})b" , "$1_"); only replaces every third b. Imho, that's one STRONG argument for the simpler approach. >> Well, nope. if you do a "ababab".replaceAll("b","_"); you'd >> want all "b"s replaced, even if not adjacent to the previous >> one. > Maybe it's just me, but "end of previous" was not clear. > If you're search the "ababab" string and you're looking for "bab" > can it find it twice? Nope, but in "babababa", if you search for \\Gbab you'll get only one match, because the second match is not adjacent to the first one. Without the \\G, the next match *may* still start adjacent ("babbab"), but *may* also start later ("babxyzbab"). Under no circumstances(*) will the second match overlap a previous one. *: except, of course, when Java's RE impl is buggy. Then all bets are off.