Reputation: 61
I am making a regex that should run through this list and return the following values.
['-- /\ 11.5', '- /\ 11.5', ' x-small', '-- x-small', 'us 8.5']
Desired output:
['11.5', '11.5', 'x-small', 'x-small', 'us 8.5']
The regex I am using:
let testRe = /(?!-)[a-zA-Z0-9\.\-]+/
The output I am getting:
['11.5', '11.5', 'x-small', 'x-small', 'us']
As you can see the problem is with getting the space between us and 8.5 to return. I've tried a lot of different variations of the regex however I can't seem to get one that will work with the others.
I basically need a regex that: starts at the first number/letter in a string, picks up anything between the first and last number/letter, and returns it.
Thanks for any insight
Upvotes: 0
Views: 86
Reputation: 47894
It appears from your sample input that you are trimming unwanted characters from the left-side of the strings. For this reason, you can merely start matching once the first letter or number is encountered. (If this logic does not hold true for all of your use cases, please provide more samples in your question that break this rule.)
Javascript Demo:
let array = ['-- /\ 11.5', '- /\ 11.5', ' x-small', '-- x-small', 'us 8.5'];
let reTest = /[a-z\d].*/i;
for (var i=0, len=array.length; i<len; ++i) {
document.write(array[i].match(reTest)+"<br>");
}
Upvotes: 0
Reputation: 23317
You can try this:
([a-zA-Z0-9.][a-zA-Z0-9.\- ]*[a-zA-Z0-9.\-])
Explanation:
[a-zA-Z0-9.]
matches letter digit or dot that should be at the beginning of the substring we are looking for[a-zA-Z0-9.\- ]*
matches also a dash -
and a space
(as both are allowed inside the substring). It can be repeated.[a-zA-Z0-9.\-]
last allowed char again can be letter, digit or dot. Using that at the end limits scope of the repetition that is inside the and assures that we match until last allowed char.Upvotes: 2