Regular Expression and Forward Slash

Matching a Forward Slash with a regex

You can escape it like this.

/\//ig; //  Matches /

or just use indexOf

if(str.indexOf("/") > -1)

Allow / forward slash in regular expression

It is easy to add a forward slash, just escape it. No need using any character references or entities.

var patt = /^(?=.*[a-zA-Z0-9.!@#&*\-\u0080-\u052F])[\/a-zA-Z0-9\s.!@#&*',\-\u0080-\u052F]*$/;
^

var patt = /^(?=.*[a-zA-Z0-9.!@#&*\-\u0080-\u052F])[\/a-zA-Z0-9\s.!@#&*',\-\u0080-\u052F]*$/;alert(patt.test("/test"));

What does the forward slash mean within a JavaScript regular expression?

The slashes indicate the start and end of the regular expression.

The g at the end is a flag and indicates it is a global search.

From the docs:

Regular expressions have four optional flags that allow for global and
case insensitive searching. To indicate a global search, use the g
flag. To indicate a case-insensitive search, use the i flag. To
indicate a multi-line search, use the m flag. To perform a "sticky"
search, that matches starting at the current position in the target
string, use the y flag. These flags can be used separately or together
in any order, and are included as part of the regular expression.

To include a flag with the regular expression, use this syntax:

 var re = /pattern/flags;

Regex - Match the characters but not the forward slash

The \S pattern matches /. You should rely on [^\/] negated character class and use anchors:

^\/test\/[^\/]+\/contact\/[^\/]+$

See the regex demo

Details

  • ^ - start of string
  • \/test\/ - /test/
  • [^\/]+ - 1+ chars other than /
  • \/contact\/ - /contact/
  • [^\/]+ - 1+ chars other than /
  • $ - end of string.

Why are regular expressions wrapped in forward slashes

For conventional/traditional reasons. Often we'd have three parts to the regex, the pattern, the substitution, and the modifiers. For example, the substitution command:

s/Hello/G'day/g

has three components: the Hello which is the pattern - we want to find "Hello", the G'day which is the substitution - we want to replace "Hello" with "G'day", and g which are the modifiers - in this case, g means to do it as many times as possible and not just once.

With some languages, they have the components as separate arguments rather than being delimited using slashes.

Often if you see it without any slashes, it means it's the pattern. If for some reason a language surrounds a pattern with slashes, you know it means it's the pattern.

Hope this helps. :)

Matching forward slash in regex

The slash is fine, the problem is that {3} is extended regular expression (ERE) syntax -- you need to pass REG_EXTENDED or use \{3\} instead (where of course in a C string those backslashes need to be doubled).



Related Topics



Leave a reply



Submit