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: Thu, 1 Mar 2018 22:31:08 -0000 (UTC) Organization: A noiseless patient Spider Lines: 34 Message-ID: References: <4a800440-39fe-4684-8369-e6a4e6b9d79f@googlegroups.com> <44c665e1-e965-4e9b-8aa0-72aa20607e63@googlegroups.com> <8c677118-8115-409d-8d3b-396e54b063ae@googlegroups.com> Reply-To: avl@logic.at Injection-Date: Thu, 1 Mar 2018 22:31:08 -0000 (UTC) Injection-Info: reader02.eternal-september.org; posting-host="807d901ffb0722c07d9ed77f22fa844a"; logging-data="2173"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+OlViKlsZX0DJJROqHC53J" User-Agent: slrn/1.0.2 (Linux) Cancel-Lock: sha1:8K0QerWkH0vhqqeYABG6bp4azVw= Xref: csiph.com comp.lang.java.programmer:38099 Eric Douglas wrote: > On Thursday, March 1, 2018 at 4:55:58 PM UTC-5, Andreas Leitgeb wrote: >> If it doesn't, feel free to post a followup with the updated pattern, >> in, spec and out strings. > That was just one of many tests, if you noticed the other one didn't work any better. > input.replaceAll( "((?:" + match + "){" + (n - 1) + "})(" + match + ")", "$1" + rep ); It's pretty normal that some attempt at writing an RE to solve a problem doesn't work at first time. Then, there's essentially two strategies: 1) randomly shuffle around the funny symbols and see if that works then. If the reshuffled variant doesn't work, either, go back to original and defend it: "tried other way, but didn't work any better." 2) analyze what the RE is really doing, and refine it to do what you want it to do. take your choice... Also you're playing it the hard way, by building up your RE from fixed and variable parts. Start with constructing the RE for a specific char and n (literally writing "{2}" (for n==3)), and only after that works, then take it apart and assemble it from literal and variable parts. It's one thing to get an RE right, but a much harder thing to get some mix of RE and Java-expressions right from scratch. PS: in the example you gave this time you do not seem to allow other stuff between the matches. It would match "bbb" and turn it to "bb_", but wouldn't match "babab", so couldn't turn that to "baba_"