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 19:03:34 -0000 (UTC) Organization: A noiseless patient Spider Lines: 27 Message-ID: References: <4a800440-39fe-4684-8369-e6a4e6b9d79f@googlegroups.com> Reply-To: avl@logic.at Injection-Date: Thu, 1 Mar 2018 19:03:34 -0000 (UTC) Injection-Info: reader02.eternal-september.org; posting-host="807d901ffb0722c07d9ed77f22fa844a"; logging-data="23661"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19RlfAXhwwkoHeSCazkOMT+" User-Agent: slrn/1.0.2 (Linux) Cancel-Lock: sha1:DGk4vwsXMJF+Wkdg6eeHI9HghhM= Xref: csiph.com comp.lang.java.programmer:38087 Eric Douglas wrote: > I hate to ask because I feel like I'm close and missing something stupid, but how do you do this? > String in = "abc aa bb cc a bb ccc a b c abc aa bbb cc babacaca"; > I've found we can replace every third space using this: > String out; > out = in.replaceAll("(?<=\\G\\S*\\s\\S*\\s\\S*)\\s", "_"); > System.out.println(out); > Result: > "abc aa bb_cc a bb_ccc _a b c_abc aa bbb_cc babacaca" > > Now I'm trying to replace the nth occurrence of a string. > The best I can find matches the nth sequential. > > int n = 2; > String repl = "b"; > out = in.replaceAll("([.]*["+repl+"]{"+(n-1)+"}[.]*)"+repl,"$1_"); [.] only matches a literal dot. That might be the root-cause of why it's not working the way you like. > System.out.println(out); > > Result: > "abc aa b_ cc a b_ ccc a b c abc aa b_b cc babacaca" > > What I'm looking for: > "abc aa _b cc a _b ccc a _ c abc aa _b_ cc ba_acaca"