Path: csiph.com!usenet.pasdenom.info!gegeweb.org!eternal-september.org!feeder.eternal-september.org!mx04.eternal-september.org!.POSTED!not-for-mail From: Jim Janney Newsgroups: comp.lang.java.programmer Subject: Re: Keeping the split token in a Java regular expression Date: Tue, 27 Mar 2012 08:15:02 -0600 Organization: thinking of Maud you forget everything else Lines: 45 Message-ID: <2pvclq9lll.fsf@shell.xmission.com> References: <48d35bc3-a391-4ccf-a222-dac64775a2f2@oq7g2000pbb.googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: mx04.eternal-september.org; posting-host="PnllQd880uOddfy6hsxHuQ"; logging-data="25240"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19KkHlpaeEx7oMXZ+bHBuyc" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:EZDHja1n6JS7xomviCe2y/fIjQI= sha1:qp4/fuCOBMkZ9UDzg9RU/gRygSw= Xref: csiph.com comp.lang.java.programmer:13224 laredotornado writes: > Hi, > > I'm using Java 6. I want to split a Java string on a regular > expression, but I would like to keep part of the string used to split > in the results. What I have are Strings like > > Fri 7:30 PM, Sat 2 PM, Sun 2:30 PM > > What I would like to do is split the expression wherever I have an > expression matching /(am|pm),?/i . Hopefully I got that right. In > the above example, I would like the results to be > > Fri 7:30 PM > Sat 2 PM > Sun 2:30 PM > > But with String.split, the split token is not kept within the > results. How would I write a Java parsing expression to do what I > want? > > Thanks, - Dave You want to match ,? only when it is preceded by (am|pm). That's what lookbehind is for: public class LookBehind { public static void main(String[] args) { String data = "Fri 7:30 PM, Sat 2 PM, Sun 2:30 PM"; String pattern = "(?i)(?<=am|pm),?"; String[] split = data.split(pattern); for (String s : split) { System.out.println("'" + s + "'"); } } } See http://www.regular-expressions.info/lookaround.html for a tutorial. -- Jim Janney