2012-07-24 114 views
1

在我的Perl程序中,我在$new中具有可變長度的字符串。以下是一些實例:從字符串中提取元素的正則表達式

$new = "sdf/wer/wewe/dfg"; 
$new = "lkjz/dfgr/wdvf"; 
$new = "asdfe"; 

我如何提取由/分隔的元素融入到使用正則表達式的陣列?

回答

3

可以使用split函數,該函數作爲參數的模式分割上,字符串分割,以及可選的次數分裂。

$new = "sdf/wer/wewe/dfg"; 
@values = split("/", $new); 
+0

這是如此簡單,我想正則表達式的! :P 謝謝你! – 2012-07-24 19:02:23

+3

@rad,那麼,'split'的第一個參數就是一個正則表達式:)順便說一句,我不想​​隱藏這個事實。我會使用'split(qr {/},$ new)'或'split(qr {\ s */\ s * /},$ new)'。 – ikegami 2012-07-24 19:24:10

+0

@ikegami,你是對的! – 2012-07-24 20:09:47

2

如果你有一個固定的分隔符,那麼正則表達式不一定是最好的選擇。分割函數是一個更好的選擇:

my @items = split "/", $new; 
2

你不說,可在要素是什麼人物,但假設他們能夠包含一切,但斜線,這將提取它們爲你。它也排除任何前導空白或空白字段。

use strict; 
use warnings; 

my @new = (
    " sdf/wer/wewe/dfg ", 
    " sdf/dfgr/wdvf ", 
    " asdfe ", 
    " first field/second field ", 
    " a/b/c/d/e/f ", 
); 

for (@new) { 
    my @fields = m|[^/\s](?:[^/]*[^/\s])?|g; 
    printf "(%s)\n", join ', ', map "'$_'", @fields; 
} 

輸出

('sdf', 'wer', 'wewe', 'dfg') 
('sdf', 'dfgr', 'wdvf') 
('asdfe') 
('first field', 'second field') 
('a', 'b', 'c', 'd', 'e', 'f')