Reputation: 6083
I need to have a regex that will check if a certain string exists in another string and has any amount of chars after that. I wrote this expression:
(somesite.com\/user\/[a-zA-Z0-9-_])\w\S
So, for example, this string www.somesite.com/user/username
should return true, while this one www.somesite.com/user
- false.
For some reason it works only if I have at least 3 chars after the somesite.com/user/
part. So somesite.com/user/me
returns false. And somesite.com/user/someuser
returns true only for somesite.com/user/som
.
The only allowed chars after the user/
part should be a-z, A_Z, 0-9, dash and underscore.
How can I make it work?
Upvotes: 1
Views: 31
Reputation: 626689
Three chars are required aftr user/
because [a-zA-Z0-9-_]\w\S
match (and thus require) three chars to exist after user/
.
You seem to need
somesite\.com\/user\/[\w-]+
See the regex demo
Note that .
should be escaped to match a literal dot. \w
usually stands for [A-Za-z0-9_]
by default, so you may shorten the pattern a bit using this shorthand character class.
Details
somesite\.com\/user\/
- a somesite.com/user/
substring[\w-]+
- 1 or more word chars (letters, digits, _
) and/or -
JS demo:
var ss = ['www.somesite.com/user/username', 'somesite.com/user/me', 'www.somesite.com/user'];
var rx = /somesite\.com\/user\/[\w-]+/g;
for (var s of ss) {
console.log(s, "=>", s.match(rx));
}
Upvotes: 2
Reputation: 813
Try (somesite.com\/user\/[a-zA-Z0-9-_]+)
You can validate your regex here: https://regex101.com/
Upvotes: 1