How to capture multiple repeated groups?

前端 未结 7 1525
傲寒
傲寒 2020-11-22 10:59

I need to capture multiple groups of the same pattern. Suppose, I have a following string:

HELLO,THERE,WORLD

And I\'ve written a following

相关标签:
7条回答
  • 2020-11-22 11:31

    After reading Byte Commander's answer, I want to introduce a tiny possible improvement:

    You can generate a regexp that will match either n words, as long as your n is predetermined. For instance, if I want to match between 1 and 3 words, the regexp:

    ^([A-Z]+)(?:,([A-Z]+))?(?:,([A-Z]+))?$
    

    will match the next sentences, with one, two or three capturing groups.

    HELLO,LITTLE,WORLD
    HELLO,WORLD
    HELLO
    

    You can see a fully detailed explanation about this regular expression on Regex101.

    As I said, it is pretty easy to generate this regexp for any groups you want using your favorite language. Since I'm not much of a swift guy, here's a ruby example:

    def make_regexp(group_regexp, count: 3, delimiter: ",")
      regexp_str = "^(#{group_regexp})"
      (count - 1).times.each do
        regexp_str += "(?:#{delimiter}(#{group_regexp}))?"
      end
      regexp_str += "$"
      return regexp_str
    end
    
    puts make_regexp("[A-Z]+")
    

    That being said, I'd suggest not using regular expression in that case, there are many other great tools from a simple split to some tokenization patterns depending on your needs. IMHO, a regular expression is not one of them. For instance in ruby I'd use something like str.split(",") or str.scan(/[A-Z]+/)

    0 讨论(0)
提交回复
热议问题