user2675345
user2675345

Reputation: 541

Refining a regex repeating group

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

Answers (5)

Bohemian
Bohemian

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

tobias_k
tobias_k

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

Ibrahim Najjar
Ibrahim Najjar

Reputation: 19423

You can do it like this:

(?:[^-]*-?){2}

Regex 101 Demo

Upvotes: 0

sp00m
sp00m

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

Leeor
Leeor

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

Related Questions