Reputation: 1670
Given the following examples:
100k melon 8
200 knife 7k
1.2m maple logs 19
I need to be able to take the first string as one group, the middle parts as another group, and the last part as the final group.
The current expression I have is this but regular expressions really throw me for a whirl:
([\d+|k])
Do any of you veterans have an idea of where I should go next or an explanation of how I can reach a solution to this?
Unfortunately, Reference - What does this regex mean? doesn't really solve my problem since it's just a dump of all of the different tokens you can use. Where I'm having trouble is putting all of that together in a meaningful way.
Upvotes: 0
Views: 115
Reputation: 10627
Okay, if I understand your question correctly, you have the following String '100k melon 8 200 knife 7k 1.2m maple logs 19'
. You should make a function that returns a .match()
:
function thrice(str){
return str.match(/(\d+\.\d+|\d+)\w?\D+(\d+\.\d+|\d+)\w?/g);
}
console.log(thrice('100k melon 8 200 knife 7k 1.2m maple logs 19'));
Otherwise, if you just want to test each String separately, you may consider:
function goodCat(str){
let g = str.match(/^(\d+\.\d+|\d+)\w?\D+(\d+\.\d+|\d+)\w?$/) ? true : false;
return g;
}
console.log(goodCat('100000k is 777 not enough 5'));
console.log(goodCat('100k melon 8'));
console.log(goodCat('200 knife 7k'));
console.log(goodCat('1.2m maple logs 19'));
Upvotes: 0
Reputation: 17238
Solution
This regex does the job
^(\S+)\s+(.*)\s+(\S+)$
See a demo here (Regex101)
Explanation
Upvotes: 0
Reputation: 3483
Here's what I came up with:
([0-9\.]+[a-z]?)\s([a-z\ ]+)\s([0-9\.]+[a-z]?)
and a quick overview of the groups:
([0-9\.]+[a-z]?)
matches any number or dot any number of times, plus an optional 1-character unit, like "k" or "m"
([a-z\ ]+)
matches letter and/or spaces. This may include a trailing or leading space, which is annoying, but I figured this was good enough.
([0-9\.]+[a-z]?)
same as the first group.
The three groups are separate by a space each.
Upvotes: 1