2015-04-25 33 views
1

我目前正在調試Perl腳本和遇到的,這將在下面的章節下面描述的一些錯誤:如何使正則表達式接受字符串以點

在劇本,我有這樣的-td變量設計接受像1n, 5n, 0.3n, 0.8n

但是,當我嘗試使用從列表中的最後兩個,該腳本不能按預期工作,並且只有當我使用列表中的前兩個時才工作正常。

給你一個概述,我寫劇本的某些部分,然後代碼後,我會說出我的擔心:

if (scalar(@ARGV) < 1){ &get_usage() }; 
# Getoptions Setup ## 
GetOptions (
    'h|help'   => \$help, 
    'v|version'  => \$version, 
    'i|input=s'  => \$input, 
    'o|output=s'  => \$output, 

    ... # more options here 

    'td=s'   => \$td_val, # this is the line in question 
    'val=s'   => \$v_var, 

    ... # more options here 

) or die get_usage(); # this will only call usage of script or help 

    ... # more codes here 

get_input_arg(); # this function will validate the entries user had inputted 

#assigning to a placeholder value for creating a new file 
$td_char="\ttd=$td_val" if $td_val; 
$td_char=" " if !$td_val; 

... # fast forward ... 

sub get_input_arg{ 

... 
# here you go, there is wrong in the following regex to accept values such as 0.8n 
unless (($td_val=~/^\d+(m|u|n|p)s$/)||($td_val=~/^\d+(m|u|n|p|s)$/)||($td_val=~/^\d+$/)){# 
print "\n-td error!\nEnter the required value!\n"; 
get_usage(); 

... # more functions here ... 

} 

對於解釋:

  1. 在控制檯用戶將輸入-td 5n
  2. 5n將被分配到td_valtd_char和用於打印以後
  3. 5n將驗證get_input_arg()功能,這將傳遞到正則表達式unless線。

對於5n輸入,腳本的工作如預期,但是當我們使用-td 0.8n,然後確認之後,它將unless行控制檯

我知道正則表達式失敗上後打印錯誤信息匹配關於使用0.8n作爲td輸入,但我不知道如何修復它。提前致謝!

+1

'$ td_val =〜/^[0-9。] + [munp] s?$ /' –

+0

我試過,但沒有w ork – Meeyaw

+0

如果您想使用特殊字符,請在其前加一個\ /\d+\.\d+/ –

回答

-1

您可以使用

unless (($td_val=~/^\d+(\.\d+)?[munp]s$/)||($td_val=~/^\d+(\.\d+)?[munps]$/)||($td_val=~/^\d+(\.\d+)?$/)) 

說明:

你的正則表達式有隻匹配整數\d+ ..所以與\d+(\.\d+)?(不可分割的一部分,後跟可選的小數部分)

DEMO更換

+0

我明白你在那裏做了什麼。無論如何感謝您的幫助 – Meeyaw

+0

高興地幫助:) –

相關問題