0

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.

Adam Chubbuck
  • 1,342
  • 4
  • 24
  • Does this answer your question? [Reference - What does this regex mean?](https://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean) – rsjaffe May 05 '20 at 00:37
  • 1
    @rsjaffe, as stated in the question, that does not answer the question. – StackSlave May 05 '20 at 00:43

3 Answers3

1

Here's what I came up with:

([0-9\.]+[a-z]?)\s([a-z\ ]+)\s([0-9\.]+[a-z]?)

enter image description here

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.

jshawl
  • 2,828
  • 2
  • 19
  • 31
0

Solution

This regex does the job

^(\S+)\s+(.*)\s+(\S+)$

See a demo here (Regex101)

Explanation

  • Explicitly match non-whitespace sequences at the start and the end of the string, resp.
  • The remainder are the middle parts surrounded by ws sequences.
collapsar
  • 15,446
  • 3
  • 28
  • 56
  • Recall that `[^\s]` is the same as `\S`. Also, this matches `melon 8 x` as the middle part of `100k melon 8 x 6` (because `.*` is greedy). – Cary Swoveland May 05 '20 at 01:18
0

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'));
StackSlave
  • 10,198
  • 2
  • 15
  • 30