Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Answer: How do I use a regex to identify a / character at the beginning of a string?

( #400698=categorized answer: print w/ replies, xml ) Need Help??

Q&A > regular expressions > How do I use a regex to identify a / character at the beginning of a string? contributed by apotheon

What many regex users don't realize is that the slashes aren't the designators for regex matching. The actual designator is the letter m, and the slashes are only delimiters. Because the most basic use of regular expressions is to match strings, however, the process of matching has been abbreviated — aliased, if you will — so that omitting the m is possible as long as the default delimiters (slashes) are used. This causes problems if the default delimiters and the string for which you're searching are one and the same, however.

Other characters can be substituted for the slash in such circumstances, or the slashes within the matching pattern can be escaped.

The escape character option is the most obvious to those who think of slashes as the actual designators of a matching regex. For such an approach, one might use either of the following code examples to search for a slash using a matching regular expression.
example 1: /^\//
example 2: m/^\//

To substitute other characters, one must be certain to use the letter m to designate the matching regular expression. I provide a couple examples of substitute delimiters.
example 1: m@^/@
example 2: m#^/#

Using alternative delimiters is something that happens "on the fly". That is to say, you don't have to predefine the use of alternate delimiters, and the next time you use a matching regexp in the same script you don't have to keep using the same alternate delimiters. Thus, you can use /^\// in a script, follow it later with m#^/# in the same script, and still later use m/^\// (all without running afoul of any restrictions in how Perl regexp syntax is used).

Comment on Answer: How do I use a regex to identify a / character at the beginning of a string?
Select or Download Code
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (10)
As of 2014-09-19 08:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (133 votes), past polls