Ruby regex split difficulty, close but not quite

I am having difficulty using a regular expression in ruby ​​to split a string along multiple delimiters, these delimiters:

  • /
  • &
  • and

each of these delimiters can have any number of spaces on either side of the delimiter, but each element can contain a valid space. great example i tested is a line1, 2 /3 and 4 12

what i would like is something like strings "1, 2 /3 and 4 12".split(regex) =>["1", "2", "3", "4 12"]

The closest I could get is /\s*,|\/|&|and \s*/, but instead of the desired results, it generates ["1", " 2 ", "3 ", "4 12"].

Understand that it is very close, and I could just cut off every subject, but be so close and knowing that it can be done, it’s conscience to me crazy. Hope someone can help me keep the madness in fear.

+3
source share
3 answers
/\s*,|\/|&|and \s*/

It analyzes how /(\s*,)|\/|&|(and \s*)/. That is, the leading \s*applies only to the comma, and the final \s*applies only to "and". Do you want to:

/\s*(,|\/|&|and )\s*/

Or to avoid capture:

/\s*(?:,|\/|&|and )\s*/
+3
source

Try .scan:

irb(main):030:0> "1, 2 /3 and 4 12".scan(/\d+(?:\s*\d+)*/)
=> ["1", "2", "3", "4 12"]
+1
source

You can try:

(?:\s*)[,\/](?:\s*)|(?:\s*)and(?:\s*)

But, as Nakilon suggested, you had better luck with scanning instead of splitting.

+1
source

Source: https://habr.com/ru/post/1771005/


All Articles