Reputation: 1303
I have this regular expression in C# language
public static bool IsValidId(string Id)
{
return Regex.IsMatch(Id, @"^([A-Za-z0-9]|[+|\?|/|\-|:|\(|\)|\.|,||]){1,35}$");
}
I am pretty confused how to use this regexp in JavaScript!, since the c# version has used @ to avoid escaping characters and since I want to use it in JavaScript es5 and I am not aware of any equivalent construct, I am confused about the characters that I should escape in JavaScript !
is it correct ? /^([A-Za-z0-9]|[+|\?|/|\-|:|\(|\)|\.|,||]){1,35}$/
Upvotes: 0
Views: 460
Reputation: 626689
You have a regex pattern like this:
^([A-Za-z0-9]|[+|\?|/|\-|:|\(|\)|\.|,||]){1,35}$
It is basically matching an alphanumeric symbol (with [A-Za-z0-9]
) or (|
) some special character (from the [+|\?|/|\-|:|\(|\)|\.|,||]
set) 1 to 35 times (as the {1,35}
limiting quantifier is used), and the whole string should match this pattern (as ^
- start of string - and $
- end of string - anchors are used).
The pattern can be written in a more linear way, just merge the 2 character classes to remove the alternation group, and set the limiting quantifier to the character class and put the hyphen at the end so as not to have to escape it:
^[A-Za-z0-9+?/:().,|-]{1,35}$
Now, the best way to use this pattern in a JS regex is by using it inside a regex literal (where /
must be escaped since it is a regex delimiter symbol):
/^[A-Za-z0-9+?\/:().,|-]{1,35}$/
Since you use Regex.IsMatch()
in C#, you are only interested in a boolean value, if a string matches the regex or not. In JS, use RegExp#test()
.
var rx = /^[A-Za-z0-9+?\/:().,|-]{1,35}$/;
var s = "Some-string01:more|here";
var result = rx.test(s);
console.log("Result:", result);
Upvotes: 2