0

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}$/

7
  • 2
    You don't need | in character class. /^([A-Za-z0-9]|[+?/:().,|]-){1,35}$/. Just remember to place - at end in character class. Commented May 1, 2017 at 11:14
  • 1
    Why avoid escaping characters? Just escape every \ by putting another backslash before it. Like ^([A-Za-z0-9]|[+|\\?|/|\\-|:|\\(|\\)|\\.|,||]){1,35}$ Commented May 1, 2017 at 11:15
  • Please post all the relevant c# code. Commented May 1, 2017 at 11:18
  • @WiktorStribiżew I added all the c# code I have. Commented May 1, 2017 at 11:26
  • 1
    You may use /^[A-Za-z0-9+?\/:().,|-]{1,35}$/.test(Id) Commented May 1, 2017 at 11:33

1 Answer 1

2

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.