Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching a Forward Slash with a regex

I don't have much experience with JavaScript but i'm trying to create a tag system which, instead of using @ or #, would use /.

var start = /#/ig; // @ Match  var word = /#(\w+)/ig; //@abc Match 

How could I use a / instead of the #. I've tried doing var slash = '/' and adding + slash +, but that failed.

like image 416
iBrazilian2 Avatar asked May 20 '13 19:05

iBrazilian2


People also ask

How do you match a forward slash in regex?

You need to escape the / with a \ . Show activity on this post. You can escape it by preceding it with a \ (making it \/ ), or you could use new RegExp('/') to avoid escaping the regex. See example in JSFiddle.

How do you escape a forward slash in regex?

You escape it by putting a backward slash in front of it: \/ For some languages (like PHP) you can use other characters as the delimiter and therefore you don't need to escape it. But AFAIK in all languages, the only special significance the / has is it may be the designated pattern delimiter.

How do you match a slash in a regular expression in Java?

If you want to match a backslash in your regular expression, you'll have to escape it. Backslash is an escape character in regular expressions. You can use '\\' to refer to a single backslash in a regular expression. However, backslash is also an escape character in Java literal strings.

How do you use forward slash in regex Python?

r'[/]*' means "Match 0 or more forward-slashes". There are exactly 0 forward-slashes between 'b' & 'c' and between 'c' & 'd'. Hence, those matches are replaced with 'a'.


2 Answers

You can escape it like this.

/\//ig; //  Matches / 

or just use indexOf

if(str.indexOf("/") > -1) 
like image 117
Ben McCormick Avatar answered Oct 07 '22 05:10

Ben McCormick


You need to escape the / with a \.

/\//ig // matches / 
like image 20
djechlin Avatar answered Oct 07 '22 05:10

djechlin