Refining a regex repeating group -
i'm trying extract 2 sides of string delimited hyphen
abc - def
at moment have
([^-]*)-([^-]*)
match 1 abc
, match 2 def
.
is there more elegant way of writing regular expression there no repeating elements? i.e. ([^-]*)
not repeated twice.
simply use [^-]+
, iterate on results.
illustration in java:
// yours matcher m1 = pattern.compile("([^-]*)-([^-]*)").matcher("abc - def"); if (m1.find()) { system.out.println(m1.group(1)); system.out.println(m1.group(2)); } // mine matcher m2 = pattern.compile("[^-]+").matcher("abc - def"); while (m2.find()) { system.out.println(m2.group()); }
outputs identical.
Comments
Post a Comment