2016-09-10 75 views
-3

我是ruby的新手,嘗試使用正則表達式。 基本上我想讀一個文件,並檢查它是否有正確的格式。如何使用正則表達式匹配此模式

Requirements to be in the correct format: 
1: The word should start with from 
2: There should be one space and only one space is allowed, unless there is a comma 
3: Not consecutive commas 
4: from and to are numbers 
5: from and to must contain a colon 

from: z to: 2 
from: 1 to: 3,4 
from: 2 to: 3 
from:3 to: 5 
from: 4 to: 5 
from: 4 to: 7 
to: 7 from: 6 
from: 7 to: 5 
0: 7 to: 5 
from: 24 to: 5 
from: 7 to: ,,,5 
from: 8 to: 5,,5 
from: 9 to: ,5 

如果我有正確的正則表達式,那麼輸出應該是:

from: 1 to: 3,4 
from: 2 to: 3 
from: 4 to: 5 
from: 4 to: 7 
from: 7 to: 5 
from: 24 to: 5 

所以在這種情況下,這些都是假的:

from: z to: 2  # because starts with z 
from:3 to: 5  # because there is no space after from: 
to: 7 from: 6  # because it starts with to but supposed to start with from 
0: 7 to: 5  # starts with 0 instead of from 
from: 7 to: ,,,5 # because there are two consecutive commas 
from: 8 to: 5,,5 # two consecutive commas 
from: 9 to: ,5 # start with comma 
+1

這個問題似乎[似曾相識](http://stackoverflow.com/questions/39422263/regular-expression-not-working-correclty/39423003#39423003)。 –

回答

1

OK,正則表達式你想要的是這樣的:

from: \d+(?:,\d+)* to: \d+(?:,\d+)* 

這裏假定在from:列中也允許有多個數字。如果沒有,你要想這一個:

from: \d+ to: \d+(?:,\d+)* 

要驗證整個文件是有效的(假設它包含所有都是這樣的一個行),你可以使用這樣的功能:

def validFile(filename) 
    File.open(filename).each do |line| 
     return false if (!/\d+(?:,\d+)* to: \d+(?:,\d+)*/.match(line)) 
    end 
    return true 
end 
0

你在找什麼叫做負向預測。具體來說,\d+(?!,,)其中說:匹配1個或更多的連續數字後面跟着2個逗號。這裏是整個事情:

str = "from: z to: 2 
from: 1 to: 3,4 
from: 2 to: 3 
from:3 to: 5 
from: 4 to: 5 
from: 4 to: 7 
to: 7 from: 6 
from: 7 to: 5 
0: 7 to: 5 
from: 24 to: 5 
from: 7 to: ,,,5 
from: 8 to: 5,,5 
from: 9 to: ,5 
" 

str.each_line do |line| 
    puts(line) if line =~ /\Afrom: \d+ to: \d+(?!,,)/ 
end 

輸出:

from: 1 to: 3,4 
from: 2 to: 3 
from: 4 to: 5 
from: 4 to: 7 
from: 7 to: 5 
from: 24 to: 5