0

I'm trying to match any string with the regex that ends with /? and extract the string before /?

Below is my code:

$input = "boringinterestingboring/?";
if($input =~ /(.*)\/?$/) {
    print "$1\n";
}
else {
    print "not matched";
}

I'm trying to capture "boringinterestingboring" using (.*) but it's not doing that, instead it captures the whole string.

How should i get only the string before /?.

Please help.

zubug55
  • 647
  • 4
  • 21

3 Answers3

2

To match everything up to, but not including, a /?:

.*(?=/\?)

If you’re not sure about escaping, you can use a character class to do the escaping for you:

.*(?=/[?])
haukex
  • 2,853
  • 8
  • 19
Bohemian
  • 365,064
  • 84
  • 522
  • 658
1

It may seem duplicate, but as the answer of your question,
Your regex need to be:

/(.*)\/\?$/

or

/(.*)(?=\/\?$)/

Example:

$input = "boringinterestingboring/?";
print "Use \$1: $1\n" if($input =~ /(.*)\/\?$/);
print "Use \$1: $1\n" if($input =~ /(.*)(?=\/\?$)/);
print "Use \$&: $&\n" if($input =~ /.*(?=\/\?$)/);

Output:

Use $1: boringinterestingboring
Use $1: boringinterestingboring
Use $&: boringinterestingboring

Different ways, same destination. But either way, you should escape ? too, or put it in [].

Tiw
  • 4,749
  • 13
  • 21
  • 32
0

Using positive lookahead. The assertion (?=..) will match /? but will not make it part of the capturing group even if it is nested in another group.

$ echo "boringinterestingboring/?" | perl -ne ' ($x)=/(boringinterestingboring(?=\/\?))/ ; print $x '
boringinterestingboring
$

Negative test case. Below prints nothing

$ echo "boringinterestingboring#?" | perl -ne ' ($x)=/(boringinterestingboring(?=\/\?))/ ; print $x '

$
stack0114106
  • 7,676
  • 2
  • 10
  • 29