user77115
user77115

Reputation: 5577

How can I get this regexp working?

Should be easy, but this regexp is not working (Perl):

^(.*?)-(.*?)(-(.*)|$)

match

a - b - c (I want $1=a, $2=b, $3=c)
a - b (I want $1=a, $2=b)

!match

abc

Any ideas welcome.
You can try it here:
https://regex101.com/r/kP0fN9/2

Upvotes: 1

Views: 53

Answers (2)

Toto
Toto

Reputation: 91385

How about:

use strict;
use warnings;
use Data::Dump qw(dump);

while(<DATA>) {
    chomp;
    my @res = $_ =~ /([^-]+)/g;
    dump@res;
}


__DATA__
a - b - c
a - b

Output:

("a ", " b ", " c")
("a ", " b")

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174696

Seems like you want something like this,

^[^-]*-(?:[^-]*-)?[^-]*$

OR

^[^-\n]*-(?:[^-\n]*-)?[^-\n]*$

DEMO

Update:

^(.*?)\s*-\s*(.*?)\s*(?:-\s*(.*)|$)

DEMO

Upvotes: 2

Related Questions