2013-10-25 48 views
1

就我所知,括號增加了優先級,允許右側的貪婪匹配優先於左側的優先級。有沒有辦法在正則表達式中強制優先(perl樣式)

我的問題是,我想抓住剩下的左手值,所以我需要將括號括起來。

有沒有其他方法可以將右手邊朝上?

示例文本:

some words  blah blah 123 

示例(錯誤)的正則表達式:

/^([\w ]+)\s{2,}([\w ]+)\s{2,}([\w ]+)$/ 

我需要\ S +爲比[\ W] +在抓取空間貪婪。我可能可以排除單詞中的多個空格與斷言相匹配,但我仍然試圖讓我的頭在他們周圍。

回答

2

你不應該試圖重疊班,貪婪或非貪婪quantifers混合。
你必須知道你想要什麼,並劃出鮮明的邊界。

# /^\s*(\w(?:[ ]?\w+)*)\s{2,}(\w(?:[ ]?\w+)*)\s{2,}(\w(?:[ ]?\w+)*)\s*$/ 

(?x)      # Modifier group, x = eXpanded 
^      # BOL 
\s*      # optional many whitespaces at start 
(\w (?: [ ]? \w+)*) # (1) word char start, word char end, optional 1 space between words 
\s{2,}     # minimum 2 whitespace 
(\w (?: [ ]? \w+)*) # (2) word char start, word char end, optional 1 space between words 
\s{2,}     # minimum 2 whitespace 
(\w (?: [ ]? \w+)*) # (3) word char start, word char end, optional 1 space between words 
\s*      # optional many witespaces before end 
$      # EOL 
4

你的理解是不正確的。圓括號不會增加優先級,只需進行分組。問題在於,量詞提前儘可能地多,因此([\w ]+)匹配直到最後兩個空白字符。你的例子不是很清楚,但你可以使用非貪婪的量詞添加額外的?

這裏測試:

#!/usr/bin/env perl 

use warnings; 
use strict; 

while (<DATA>) { 
     m/^([\w ]+?)\s{2,}([\w ]+?)\s{2,}([\w ]+?)$/; 
     print "$1 -- $2 -- $3\n"; 
} 

__DATA__ 
some words  blah blah 123 

國債收益率:

some words -- blah blah -- 123 
+0

關於優先順序,我參考了http://docstore.mik.ua/orelly/perl3/lperl/ch08_05.htm – t0mmyt

相關問題