Reputation: 541
I'm trying to extract two sides of a string delimited by a hyphen
abc - def
At the moment I have
([^-]*)-([^-]*)
Match 1 would be abc
and match 2 would be def
.
Is there a more elegant way of writing this regular expression so that there are no repeating elements? i.e. ([^-]*)
is not repeated twice.
Upvotes: 3
Views: 166
Reputation: 424983
Use a non-greedy match:
(.*?)-(.*)
See a live demo showing it working.
I don't think it can be done more simply than this.
Upvotes: 1
Reputation: 82889
If your regex is more complex, you could split it up into smaller chunks and then reuse those.
For your example this could look like this (Java):
String side = "([^-]*)";
String regex = side + "-" + side;
However, while this is useful for repeated complex regexes (think e-mail validation and such), in your case the version with repetitions is perfectly okay.
You can refer to what was matched in an earlier group by using ([^-]*)-\1
, but this will only match if the two sides are equal, not if they match the same pattern, i.e., it would match "abc-abc"
, but not "abc-def"
.
Upvotes: 0
Reputation: 48807
Simply use [^-]+
and iterate over the 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 are identical.
Upvotes: 1
Reputation: 19706
You could just match (.*)-(.*)
, the hyphen would still have to get matched so it would split the 2 expressions.
By the way, you can try checking online on sites like this - http://regexpal.com/
Upvotes: 0