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
  • 729
  • 7
  • 27

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,973
  • 9
  • 21
Bohemian
  • 412,405
  • 93
  • 575
  • 722
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 [].

Til
  • 5,150
  • 13
  • 26
  • 34
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
  • 8,534
  • 3
  • 13
  • 38