Link to home
Create AccountLog in
Avatar of bamapie

asked on

Very simple regex-curiosity question

I guess the forward slash doesn't mean what I thought it meant.  And I thought it meant nothing.

Let's say I have a URL like:

and I search this string for the regex /162/.

I thought that would match.  It doesn't.

regex 162 DOES match.

So what exactly do the forward slashes here mean, and why did my including them kill my ability to match?

What I am really wanting to do is the equivalent of *162*.  But I know that I probably don't need to tell regex [wildcard]162[wildcard], so in my feeble regex memory, I thought I had to use slashes to indicate that this is the pattern I'm trying to match anywhere in the text.

I'm basically fooling around and trying to do a string .contains, but using regex.  Meaning, just simply checking the source text to see if it contains a substring.

Avatar of David Johnson, CD
David Johnson, CD
Flag of Canada image

then all you need is / and your string
i.e. /162/.
Avatar of Dr. Klahn
Dr. Klahn

Link to home
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of bamapie


My question has a typo...a period where I ended a sentence, but it looks like it's part of the regex.

The expression


is what doesn't match in the term


and I can't understand why.  Meanwhile, the same expression without slashes:


DOES work.  What's the difference?  Why do the slashes not match?  Don't they basically mean nothing?

It does not match because:

The regex /162/. means:

Match the string "/162/".
 With the slashes.  Slashes are not string delimiters or special characters, so they are part of the match and must be matched for the regex to match.
It really depends on your regex engine. In Perl and Javascript, forward slashes are delimiters for the pattern. So given the following Javascript:

var reg = /abc/;

Open in new window

...the slashes mean nothing to the regex itself--they merely delineate the regex literal. In C# however:

Regex reg = new Regex("/abc/");

Open in new window the slashes actually mean slashes in the target string (because slashes don't have special meaning in the C# regex engine.