Avatar of bamapie
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.

Thanks
Regular Expressions

Avatar of undefined
Last Comment
kaufmed

8/22/2022 - Mon
David Johnson, CD

then all you need is / and your string
i.e. /162/.

https://regex101.com/r/qZAJeL/2
ASKER CERTIFIED SOLUTION
Dr. Klahn

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
bamapie

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

The expression

/162/

is what doesn't match in the term

http://localhost:16246/

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

162

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

Thanks
Dr. Klahn

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.
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
kaufmed

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


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