Ruby Regular Expressions Help

I am trying to parse a regular expression pattern in Ruby. The pattern is similar to

<number>? <comma>? <number>? <term>*

Where:

  • number is one or more digits
  • comma ","
  • termhas the form [.*]or[^.*]

And I'm trying to fix numbers and all terms. To clarify, here are a few examples of valid patterns:

5,50[foo,bar]
5,[foo][^apples]
10,100[baseball][^basketball][^golf]
,55[coke][pepsi][^drpepper][somethingElse]

Firstly, I would like to seize 5, 50and [foo,bar] in the second case I would like to capture 5, [foo]and [^apples]etc.

The sample I came across is:

/(\d+)?,?(\d+)?(\[\^?[^\]]+\])+/

but this only matches the numbers and the last term. If I delete +at the end, then it will only match the first member.

+3
source share
2 answers

, , , , +, , ..

/(\d+)?,?(\d+)?((\[\^?[^\]]+\])+)/

, \d, (\d*) (\d+)?...

, :

matches = [ "5,50[foo,bar]",
            "5,[foo][^apples]",
            "10,100[baseball][^basketball][^golf]",
            ",55[coke][pepsi][^drpepper][somethingElse]"
          ]

re = Regexp.new('(\d*),?(\d*)((\[\^?[^\]]+\])+)')

matches.each do |match|
  m = re.match(match)

  puts "\nMatching: #{match}"
  puts "--------------------"

  puts "Match 1: #{m[1]}"
  puts "Match 2: #{m[2]}"
  puts "Match 3: #{m[3]}"
end

:

Matching: 5,50[foo,bar]
--------------------
Match 1: 5
Match 2: 50
Match 3: [foo,bar]

Matching: 5,[foo][^apples]
--------------------
Match 1: 5
Match 2: 
Match 3: [foo][^apples]

Matching: 10,100[baseball][^basketball][^golf]
--------------------
Match 1: 10
Match 2: 100
Match 3: [baseball][^basketball][^golf]

Matching: ,55[coke][pepsi][^drpepper][somethingElse]
--------------------
Match 1: 
Match 2: 55
Match 3: [coke][pepsi][^drpepper][somethingElse]

2

, J -_-L scan, :

m[3].scan(/\[\^?[^\]]+\]/)
+1

, - .

(, ) scan (, (\[\^?[^\]]+\])), .

+1

All Articles