Reputation: 703
I am trying to write a regex pattern that grabs string between the first occurrence of character where it begins with "/" and may end with either "/" or "//" or none. For example -
/test1/code1
/test/code1/code2
/test/code1//code2
All of above should return code1.
I tried following regex -
\/+.*?(\/|\/\/)(.*)
However, this only stops at / following test1 and returns everything. i.e. /code1//code2.
Any suggestion on how I can ensure that the look up is for beginning with / and ending with either / or // or none?
Upvotes: 0
Views: 54
Reputation: 91375
This one should do the job:
/.+?/([^/]+)(?:/|$)
The result is in group 1.
Explanation:
/ : a slash
.+? : one or more any character not greedy
/ : a slash
([^/]+) : one or more any character that is not a slash
(?:/|$) : Non capturing group either a slash or line end
Here is a perl script using this regex:
#!/usr/bin/perl
use Modern::Perl;
use Data::Dumper;
my $re = qr!/.+?/([^/]+)(?:/|$)!;
while(<DATA>) {
chomp;
say (/$re/ ? "OK: \$1=$1\t $_" : "KO: $_");
}
__DATA__
/test1/code1
/test/code1/code2
/test/code1//code2
Output:
OK: $1=code1 /test1/code1
OK: $1=code1 /test/code1/code2
OK: $1=code1 /test/code1//code2
Upvotes: 1