2013-03-22 52 views
0

實施例的數據中指定的長度的字符串的:解析與串

029Extract此特定字符串。不要捕捉其他東西。

在上面的例子中,我想捕獲定義n值的3位數字後面的前n個字符。 I.E. 29個字符「提取此特定字符串」。

我可以在循環內做到這一點,但速度很慢。我希望(如果可能的話)用單個正則表達式來實現這一點,而不是使用某種反向引用。例如:

(\d{3})(.{\1}) 
+0

你使用什麼編程語言? – 2013-03-22 12:08:55

+0

我可以靈活運用PHP,Javascript和其他一些工具來處理相同的數據。 – 2013-03-22 12:10:23

+2

您將無法將「29」解釋爲正則表達式只能使用正則表達式讀取的字符數。你需要首先提取29,然後建立你的表情。無論如何,我不認爲正則表達式是真正的保證。 – 2013-03-22 12:10:24

回答

1

用perl,你可以這樣做:

my $str = '029Extract this specific string. Do not capture anything else.'; 
$str =~ s/^(\d+)(.*)$/substr($2,0,$1)/e; 
say $str; 

輸出:

Extract this specific string. 
+0

這是一個明智的解決方案。 – 2013-03-22 13:58:30

+0

@Balthus:謝謝。 – Toto 2013-03-22 14:02:34

0

你確定你需要一個正則表達式嗎?

https://stackoverflow.com/tags/regex/info

傻瓜拉什在天使不敢涉足

的巨大力量和現代的正則表達式的表現力 可以輕信勾引 - 或者魯莽 - 成嘗試使用 定期他們遇到的每個字符串相關任務的表達式。 這是一般一個壞主意,...

這裏有一個的Python三內膽:

foo = "029Extract this specific string. Do not capture anything else." 
substr_len = int(foo[:3]) 
print foo[3:substr_len+3] 

這裏還有一個PHP三內膽:

$foo = "029Extract this specific string. Do not capture anything else."; 
$substr_len = (int) substr($foo,0,3); 
echo substr($foo,3,substr_len+3); 
0

你不能用單一的正則表達式做了,你可以使用知識,其中正則表達式停止處理使用SUBSTR。例如在JavaScript中,你可以做這樣的事情http://jsfiddle.net/75Tm5/

var input = "blahblah 011I want this, and 029Extract this specific string. Do not capture anything else."; 
var regex = /(\d{3})/g; 
var matches; 
while ((matches = regex.exec(input)) != null) { 
    alert(input.substr(regex.lastIndex, matches[0])); 
} 

這將返回兩條線:

I want this 
Extract this specific string. 

取決於你真正想要的,你可以修改正則表達式匹配只能從行開始起數,只匹配第一個匹配等