How can I build a regex to match a value?
I need a regex that matches this kind of strings:
brand-new-car
brand-new-car-1
brand-new-car-100
307
and I just need to catch the "name" regardless of whether the string has -count
; like 开发者_开发百科this:
brand-new-car
brand-new-car
brand-new-car
307
This regex does not work properly. Its $1
is the full string, not without -count
.
(\S+)(?:-\d+|)$
You need to make the first capture group "lazy" or non-greedy.
var re = new RegExp("^(\\S+?)(?:-\\d+)?$");
var testStrings = [
"brand-new-car",
"brand-new-car-1",
"brand-new-car-100",
"307"
];
for (var i=0; i<testStrings.length; i++) {
var result = re.exec(testStrings[i]);
say("result: " + result);
}
The results:
result: brand-new-car,brand-new-car
result: brand-new-car-1,brand-new-car
result: brand-new-car-100,brand-new-car
result: 307,307
Try this (?xms)(^[\w-]+.*?)(?=[\w-]+|\Z) Here, below is an image of regex buddy
where you can catch the "name" regardless of whether the string has -count the yellow and blue foreground highlights the different selections.
Just remove the pipe '|', then it works
(\S+)(?:-\d+)$
Checked here rubular
精彩评论