2013-07-20 33 views
-1

我有一個Perl腳本,它匹配以(字母數字或下劃線)開頭的行,後跟任意數量的空格,後跟另一個(字母數字或下劃線)。我現在意識到,對於第二個(字母數字或下劃線),我還需要包括這可能是負數(例如-50)的可能性。我怎樣才能做到這一點?在perl中匹配負數和非負數

原始代碼:

if (/^\w[\s]+\w/ and not /^A pdb file/) { 
...doSomething 
} 

未成功嘗試的東西,如:

if (/^\w[\s]+\-*w/ and not /^A pdb file/) 
if (/^\w[\s]+\-{0,1}w/ and not /^A pdb file/) 
if (/^\w[\s]+\w|-\w/ and not /^A pdb file/) 

感謝。

+1

你想也張貼樣本輸入和期望的結果? – thb

+0

奇怪的是,前2個不起作用; FWIW你不需要逃避'-',因爲它在字符類別之外沒有任何特殊之處。 – doubleDown

+0

@thb:謝謝,我會的,但它現在正在工作:o)。 DoubleDown:哦,對,謝謝你,我會記住的! – LanneR

回答

1

這是否符合您的需求?

/^\w+\s*-?\w+$/ 

它說比賽:

  • \w+:任意數量的字母數字字符(包括下劃線)
  • \s*:任意數量的空格(如果你需要至少在一個空間,使用\s+
  • -?:可選短劃線
  • \w+:任意數量的字母數字字母ers(包括下劃線)。如果這組字符只能是數字,則使用\d+代替。
+0

當然。非常感謝! – LanneR

+0

+1。從技術上講,我不確定這是否與OP的規格完全匹配(因爲它會匹配例如'12-bar',即使'-bar'不是「負數」),但它似乎是保留OP目前的做法。 – ruakh

+0

@ruakh:同意/謝謝。我更新了答案。 –

-2

嘗試:

m{ 
    \A   # start of the string 
    \w   # a single alphanumeric or underscore 
    \s+  # one or more white space 
    (?:  # non-capturing grouping 
     \-  # a minus sign 
     \d+ # one or more digits 
    )?   # match entire group zero or one time 
    \w   # a single alphanumeric or underscore 
}msx;