Matching a Forward Slash with a regex - javascript

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.

You can escape it like this.
/\//ig; // Matches /
or just use indexOf
if(str.indexOf("/") > -1)

You need to escape the / with a \.
/\//ig // matches /

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.
'/'.match(/\//) // matches /
'/'.match(new RegExp('/') // matches /

If you want to use / you need to escape it with a \
var word = /\/(\w+)/ig;

In regular expressions, "/" is a special character which needs to be escaped (AKA flagged by placing a \ before it thus negating any specialized function it might serve).
Here's what you need:
var word = /\/(\w+)/ig; // /abc Match
Read up on RegEx special characters here: http://www.regular-expressions.info/characters.html

You can also work around special JS handling of the forward slash by enclosing it in a character group, like so:
const start = /[/]/g;
"/dev/null".match(start) // => ["/", "/"]
const word = /[/](\w+)/ig;
"/dev/null".match(word) // => ["/dev", "/null"]

I encountered two issues related to the foregoing, when extracting text delimited by \ and /, and found a solution that fits both, other than using new RegExp, which requires \\\\ at the start. These findings are in Chrome and IE11.
The regular expression
/\\(.*)\//g
does not work. I think the // is interpreted as the start of a comment in spite of the escape character. The regular expression (equally valid in my case though not in general)
/\b/\\(.*)\/\b/g
does not work either. I think the second / terminates the regular expression in spite of the escape character.
What does work for me is to represent / as \x2F, which is the hexadecimal representation of /. I think that's more efficient and understandable than using new RegExp, but of course it needs a comment to identify the hex code.

Forward Slash is special character so,you have to add a backslash before forward slash to make it work
$patterm = "/[0-9]{2}+(?:-|.|\/)+[a-zA-Z]{3}+(?:-|.|\/)+[0-9]{4}/";
where / represents search for /
In this way you

For me, I was trying to match on the / in a date in C#. I did it just by using (\/):
string pattern = "([0-9])([0-9])?(\/)([0-9])([0-9])?(\/)(\d{4})";
string text = "Start Date: 4/1/2018";
Match m = Regex.Match(text, pattern);
if (m.Success)
{
Console.WriteLine(match.Groups[0].Value); // 4/1/2018
}
else
{
Console.WriteLine("Not Found!");
}
JavaScript should also be able to similarly use (\/).

Related

How to deal with backslash concatenation in RegExp breaking expressions, e.g. those that contain capturing groups brackets?

Creating RegEx and combining it with variables that are strings with a certain pattern doesn't always work out well, if the pattern doesn't change to work with the string.
"\\" + ) = \) in RegEx. Which is an escaped ) and not the closing bracket of a capturing group anymore.
"\\\\" + ) = \\) in RegEx. Here \ successfully gets escaped and the capturing group does not break.
In a normal string or RegEx expression with // only, so no concatenation, this "\\" would be working fine as an escaped backslash \.
The problem is, in RegEx the \ is also used for something.
What I am wondering is, if there's a way to make something flexible. That would prevent a pattern like this to match , breaking when combined together. Example, matching example\.
"(" + "example\\" + ")"
This one when combined together breaks, because when used as a RegExp, the \ gets escaped, and the capturing group breaks.
To fix it, it would have to look like this
"(" + "example\\" + "\\)"
Here, \ one backlash gets escaped and then another one gets escaped, and together in RegEx, it would result into one escaped bracket \
because what I basically created was \\ when combining it all together.
The problem is, this breaks again, if there wouldn't be \\ infront of example.
 
Here is an example code.
To explain, the function matches the path after example_folder with strings in the matchingArray that end with a \. Because it's in a string, I have to do \\ so that it appears as a \ backslash.
class example_options {
matchingArray = ["example\\", "example\\\\special\\", "something_else\\"]
}
function example(options) {
if (typeof(options) != "object") {
options = new example_options()
}
var test = `"example_folder\\example\\special\\test.txt"`
for (let i=0; i < options.matchingArray.length; i++) {
var regexPattern = new RegExp(`(?:example_folder\\\\)(${options.matchingArray[i]}\\)`)
var match = test.match(regexPattern)
if (match) {
console.log(match, options.matchingArray[i])
}
}
}
example()
example() executes the function, if you would be running it, which successfully works.
But the problem is the flexibility of it.
I wouldn't have to backlash it twice, if the RegEx would have been constructed without using string, but the slashes /:
var regexPattern = new RegExp(/(?:example_folder\\)(example\\special\\)/)
matchingArray = ["example\\", "example\\\\special\\", "something_else\\"] here I had to add \\\\, because in RegEx a \ is also used for its own thing.
At the end of the expression here:
var regexPattern = new RegExp(`(?:example_folder\\\\)(${options.matchingArray[i]}\\)`)
I had to add a \\at the end.
This would mean that in RegEx it ends up like this \) and the capturing group gets destroyed. However, since I have backslashes in the matchingArray. When all of this gets combined at the end, the RegEx near the bracket looks like this \\) and the capturing group is preserved.
Is there a way to deal with this issue?
What if I wanted the matchingArray to be like this? To be compatible with other things that aren't RegEx.
matchingArray = ["example\\", "example\\special\\", "something_else\\"]
If I would do this, it wouldn't work with RegEx anymore, because this example\\special\\ would end up like this example\special\. Then the issue would be this \s.
The other issue is that, I have to add this at the end \\) of the RegEx expression. But I only need to do that, if I know that there is going to be a \\ at the end, when combining the string.
And for the otherway around, if I would have a string in the matchingArray that wouldn't be ending with a backslash, then the RegEx would break because it would end up like this \) causing Unterminated group.
 
A possible idea that I have, is that all \ could be converted into /, but what if you can't do that?
I don't see an issue doing that however, because I would be able to convert the / back into \ at any time. It would be an issue if those mixed slashes need to be preserved, but this would probably an even more specific problem.
But are there other ways?

Regular expression didn't matched the actual service, getting pattern mismatched error

Main service : "/xxxxx/yyyyy/200426792?limit=100&offset=0"
I tried with regex : "/xxxxx/yyyyy/\\d+/[?]limit[=]100&offset[=]0"
Could you please help for this.
You need to escape your forward slashes / to indicate the the / is part of the string and not part of the regular expression. To escape your forward slashes add a backslash before them. Also, your regex is currently expecting a / after your number sequence specified by \d+/...
Fixing this all this will give you:
\/xxxxx\/yyyyy\/\d+[?]limit[=]100&offset[=]0
Which will successfully match:
/xxxxx/yyyyy/200426792?limit=100&offset=0
See example below:
const str = "/xxxxx/yyyyy/200426792?limit=100&offset=0";
const regex = /\/xxxxx\/yyyyy\/\d+[?]limit[=]100&offset[=]0/g;
console.log(regex.test(str)); // true indicates that it matches

Javascript Regex for a partial string with slash [duplicate]

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.
You can escape it like this.
/\//ig; // Matches /
or just use indexOf
if(str.indexOf("/") > -1)
You need to escape the / with a \.
/\//ig // matches /
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.
'/'.match(/\//) // matches /
'/'.match(new RegExp('/') // matches /
If you want to use / you need to escape it with a \
var word = /\/(\w+)/ig;
In regular expressions, "/" is a special character which needs to be escaped (AKA flagged by placing a \ before it thus negating any specialized function it might serve).
Here's what you need:
var word = /\/(\w+)/ig; // /abc Match
Read up on RegEx special characters here: http://www.regular-expressions.info/characters.html
You can also work around special JS handling of the forward slash by enclosing it in a character group, like so:
const start = /[/]/g;
"/dev/null".match(start) // => ["/", "/"]
const word = /[/](\w+)/ig;
"/dev/null".match(word) // => ["/dev", "/null"]
I encountered two issues related to the foregoing, when extracting text delimited by \ and /, and found a solution that fits both, other than using new RegExp, which requires \\\\ at the start. These findings are in Chrome and IE11.
The regular expression
/\\(.*)\//g
does not work. I think the // is interpreted as the start of a comment in spite of the escape character. The regular expression (equally valid in my case though not in general)
/\b/\\(.*)\/\b/g
does not work either. I think the second / terminates the regular expression in spite of the escape character.
What does work for me is to represent / as \x2F, which is the hexadecimal representation of /. I think that's more efficient and understandable than using new RegExp, but of course it needs a comment to identify the hex code.
Forward Slash is special character so,you have to add a backslash before forward slash to make it work
$patterm = "/[0-9]{2}+(?:-|.|\/)+[a-zA-Z]{3}+(?:-|.|\/)+[0-9]{4}/";
where / represents search for /
In this way you
For me, I was trying to match on the / in a date in C#. I did it just by using (\/):
string pattern = "([0-9])([0-9])?(\/)([0-9])([0-9])?(\/)(\d{4})";
string text = "Start Date: 4/1/2018";
Match m = Regex.Match(text, pattern);
if (m.Success)
{
Console.WriteLine(match.Groups[0].Value); // 4/1/2018
}
else
{
Console.WriteLine("Not Found!");
}
JavaScript should also be able to similarly use (\/).

How to convert a C# regex to javascript? [duplicate]

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.
You can escape it like this.
/\//ig; // Matches /
or just use indexOf
if(str.indexOf("/") > -1)
You need to escape the / with a \.
/\//ig // matches /
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.
'/'.match(/\//) // matches /
'/'.match(new RegExp('/') // matches /
If you want to use / you need to escape it with a \
var word = /\/(\w+)/ig;
In regular expressions, "/" is a special character which needs to be escaped (AKA flagged by placing a \ before it thus negating any specialized function it might serve).
Here's what you need:
var word = /\/(\w+)/ig; // /abc Match
Read up on RegEx special characters here: http://www.regular-expressions.info/characters.html
You can also work around special JS handling of the forward slash by enclosing it in a character group, like so:
const start = /[/]/g;
"/dev/null".match(start) // => ["/", "/"]
const word = /[/](\w+)/ig;
"/dev/null".match(word) // => ["/dev", "/null"]
I encountered two issues related to the foregoing, when extracting text delimited by \ and /, and found a solution that fits both, other than using new RegExp, which requires \\\\ at the start. These findings are in Chrome and IE11.
The regular expression
/\\(.*)\//g
does not work. I think the // is interpreted as the start of a comment in spite of the escape character. The regular expression (equally valid in my case though not in general)
/\b/\\(.*)\/\b/g
does not work either. I think the second / terminates the regular expression in spite of the escape character.
What does work for me is to represent / as \x2F, which is the hexadecimal representation of /. I think that's more efficient and understandable than using new RegExp, but of course it needs a comment to identify the hex code.
Forward Slash is special character so,you have to add a backslash before forward slash to make it work
$patterm = "/[0-9]{2}+(?:-|.|\/)+[a-zA-Z]{3}+(?:-|.|\/)+[0-9]{4}/";
where / represents search for /
In this way you
For me, I was trying to match on the / in a date in C#. I did it just by using (\/):
string pattern = "([0-9])([0-9])?(\/)([0-9])([0-9])?(\/)(\d{4})";
string text = "Start Date: 4/1/2018";
Match m = Regex.Match(text, pattern);
if (m.Success)
{
Console.WriteLine(match.Groups[0].Value); // 4/1/2018
}
else
{
Console.WriteLine("Not Found!");
}
JavaScript should also be able to similarly use (\/).

Creating javascript regex tp replace characters using whitelist

I'm trying to create a regex which will replace all the characters which are not in the specified white list (letters,digits,whitespaces, brackets, question mark and explanation mark)
This is the code :
var regEx = /^[^(\s|\w|\d|()|?|!|<br>)]*?$/;
qstr += tempStr.replace(regEx, '');
What is wrong with it ?
Thank you
The anchors are wrong - they only allow the regex to match the entire string
The lazy quantifier is wrong - you wouldn't want the regex to match 0 characters (if you have removed the anchors)
The parentheses and pipe characters are wrong - you don't need them in a character class.
The <br> is wrong - you can't match specific substrings in a character class.
The \d is superfluous since it's already contained in \w (thanks Alex K.!)
You're missing the global modifier to make sure you can do more than one replace.
You should be using + instead of * in order not to replace lots of empty strings with themselves.
Try
var regEx = /[^\s\w()?!]+/g;
and handle the <br>s independently (before that regex is applied, or the brackets will be removed).
You'll want to use the g (global) modifier:
var regEx = /^[^(\s|\w|\d|()|?|!|<br>)]*?$/g; // <-- `g` goes there
qstr += tempStr.replace(regEx, '');
This allows your expression to match multiple times.

Categories