Mayou
Mayou

Reputation: 8818

Decoding a regular expression in Perl

I am trying to decode the following Perl regular expression:

$fname =~ /\/([^\/]+)\.txt$/

What are we trying to match for here?

Upvotes: 0

Views: 150

Answers (2)

aliteralmind
aliteralmind

Reputation: 20163

\/([^\/]+)\.txt

Regular expression visualization

This regular expression matches a file name, as it exists in a path

  • Minus the extension, and
  • Only when (or starting where) the path begins with an up-right slash.

Examples:

\folder\path\file.txt

Nothing is matched.

folder/path/file.txt

file.txt is matched (and file is placed in capture group 1: $1).

/folder/path/file.txt

Again, file.txt is matched (and file captured).

You can try it yourself at Debuggex

Upvotes: 3

friedo
friedo

Reputation: 66947

Here's how you break it down.

  • \/ - the literal character /
  • (...) - followed by a group that will be captured to $1
    • [ ... ] - a character class
      • ^ - in a character class, this means take the inversion of the specified set
      • \/ - the literal character /
    • + - one or more times
  • \. - the literal character .
  • txt - the literal string txt
  • $ - the end of the string

So, in other words, this is trying to match "anything with a / followed by one or more characters that are not /, followed by .txt, followed by the end of the string, and put the part before .txt into $1"

Upvotes: 5

Related Questions