Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Knute Johnson Newsgroups: comp.lang.java.programmer Subject: Re: regex puzzle Date: Wed, 09 Apr 2014 18:24:32 -0700 Organization: A noiseless patient Spider Lines: 56 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Thu, 10 Apr 2014 01:24:31 +0000 (UTC) Injection-Info: mx05.eternal-september.org; posting-host="aba33539224e5c782fe0c4053f7756fd"; logging-data="13331"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/+8LqYhmEXu0CNyPJD+cdF" User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:24.0) Gecko/20100101 Thunderbird/24.4.0 In-Reply-To: Cancel-Lock: sha1:OGBWnyEaJasI0IW4wQ70/gfnXNA= Xref: csiph.com comp.lang.java.programmer:28011 On 4/9/2014 16:24, Roedy Green wrote: > On Wed, 09 Apr 2014 16:14:45 -0700, Roedy Green > wrote, quoted or indirectly quoted > someone who said : > >> nope 1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20 >> >> hopefully a little more terse. >> >> and would not match 2099 > > I think you need a new regex operator that collects characters 0-9, > 0-9\. etc then parses a number, then compares it with low and high > bound in the regex operator. > > It seems like such a simple problem. > > Regex gets foiled so easily, like parsing HTML tags when they don't > appear in canonical order. > import java.util.regex.*; public class test5 { public static void main(String[] args) { String sequence = "1..20"; String subject = "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20"; System.out.println(matchSeq(sequence,subject) ? "matches" : "no match"); } public static boolean matchSeq(String seq, String subject) { Pattern p1 = Pattern.compile("(\\d+)\\.\\.(\\d+)"); Matcher m1 = p1.matcher(seq); if (m1.matches()) { int from = Integer.parseInt(m1.group(1)); int to = Integer.parseInt(m1.group(2)); String s2 = Integer.toString(from); for (int i=from+1; i<=to; i++) s2 = s2.concat(String.format(" %d",i)); Pattern p2 = Pattern.compile(s2); Matcher m2 = p2.matcher(subject); return m2.matches(); } else { throw new IllegalArgumentException("bad sequence"); } } } -- Knute Johnson