开发者

Ruby regex that splits on newline, space, or comma

开发者 https://www.devze.com 2023-02-10 16:31 出处:网络
Input: f = [\"happy days\", \"happy\\ndays\", \"h开发者_Python百科appy,days\", \"happy, days\"] patt = /some_regex/

Input:

     f = ["happy days",
         "happy\ndays",
         "h开发者_Python百科appy,days",
         "happy, days"]

     patt = /some_regex/

My desired output after splitting each string in f on patt is ["happy", "days"].

Many thanks!


Try this as your pattern:

/\W+/

It matches any number of non-word characters.

Example code:

result = f.map{|s| s.split(/\W+/) }

See it working online: ideone


Or /[\n ,]+/


Try this:

f.map{ |s| s.split /[,\s]+/}

=> [["happy", "days"], ["happy", "days"], ["happy", "days"], ["happy", "days"]]


Loop over the array, using String#scan looking for words:

f = [
  "happy days",
  "happy\ndays",
  "happy,days",
  "happy, days"
]

require 'pp'
pp f.map{ |s| s.scan(/\w+/) }

>> [["happy", "days"], ["happy", "days"], ["happy", "days"], ["happy", "days"]]


irb(main):242:0> "a\nb".split(/\n/)
[
    [0] "a",
    [1] "b"
]


If you need to split on "comma with space" or "newline" then try this

"your string".replace(/^\s+$/mg, '\n').replace(/(,\s)|\n+/gm, '~').split('~')

basically this particular regex will help

/(,\s)|\n+/gm

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号