0

I have some doubts regarding RegEx in JavaScript as I am not good in RegEx.

I have a String and I want to compare it against some array of RegEx expressions.

First I tried for one RegEx and it's not working. I want to fix that also.

function check(str){
var regEx = new RegEx("(users)\/[\w|\W]*");
var result = regEx.test(str);
if(result){
//do something
}
}

It is not working properly. If I pass users, it doesn't match. If I pass users/ or users/somestring, it is matching.

If I change the RegEx to (usersGroupList)[/\w|\W]*, then it is matching for any string that contains the string users

fdgdsfgguserslist/data

I want to match like if string is either users or it should contain users/something or users/

And also I want the string to compare it with similar regex array.

I want to compare the string str with users, users/something, list, list/something, anothermatch, anothermatch/something. If if it matches any of these expression i want to do something.

How can I do that?

Thanks

1
  • Out of interest what is your thinking behind [\w|\W]*? These cancel each other out, so this will in fact match everything, including other /s. If that is what you want then just use .* Commented Dec 11, 2014 at 10:27

3 Answers 3

2

Then, you'll have to make the last group optional. You do that by capturing the /something part in a group and following it with ? which makes the previous token, here the captured group, optional.

var regEx = new RegExp("(users)(\/[\w|\W]*)?");
Sign up to request clarification or add additional context in comments.

3 Comments

Cool. It worked for one. How can I do for An Array of expressions? Do I need to loop and create RegEx objects and match??
This 1. does not cover array of keys 2. matches spurious beginning of the string (e.g. "fdgdsfgguserslist/data")
@TGMCians just another one please
1

What about making:

  1. the last group optional
  2. starting from beginning of the string

Like this:

var regEx = new RegExp("^(users)(\/[\w|\W]*)?");

Same applies for all the others cases, e.g. for list:

var regEx = new RegExp("^(list)(\/[\w|\W]*)?");

All in One Approach

var regEx = new RegExp("^(users|list|anothermatch)(\/[\w|\W]*)?");

Even More Generic

var keyw = ["users", "list", "anothermatch"];
var keyws = keyw.join("|"); 
var regEx = new RegExp("^("+keyws+")(\/[\w|\W]*)?");

2 Comments

Can I create array of RegEx expressions and test?
You can do all at once listing the keywords in a group with | (or) condition.
0

You haven't made the / optional. Try this instead

(users)\/?[\w|\W]*

1 Comment

this will match usersfhkfhsfd

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.