簡體   English   中英

用正則表達式解析字符串

[英]parse string with regular expression

我試圖解析此字符串:

$right = '34601)S(1,6)[2] - 34601)(11)[2] + 34601)(3)[2,4]';

使用以下正則表達式:

const word = '(\d{3}\d{2}\)S{0,1}\([^\)]*\)S{0,1}\[[^\]]*\])';
preg_match('/'.word.'{1}(?:\s{1}([+-]{1})\s{1}'.word.'){0,}/', $right, $matches);
print_r($matches);

我想像這樣返回數組:

Array
(
    [0] => 34601)S(1,6)[2] - 34601)(11)[2] + 34601)(3)[2,4]
    [1] => 34601)S(1,6)[2]
    [2] => -
    [3] => 34601)(11)[2]
    [4] => +
    [5] => 34601)(3)[2,4]
)

但我只返回以下內容:

Array
(
    [0] => 34601)S(1,6)[2] - 34601)(11)[2] + 34601)(3)[2,4]
    [1] => 34601)S(1,6)[2]
    [2] => +
    [3] => 34601)(3)[2,4]
)

我認為,這是因為單詞中的[^)] *或[^]] *,但是我應該如何以其他方式更正regexp以使其匹配?

我嘗試指定它:

\d+(?:[,#]\d+){0,}

所以單詞變成

const word = '(\d{3}\d{2}\)S{0,1}\(\d+(?:[,#]\d+){0,}\)S{0,1}\[\d+(?:[,#]\d+){0,}\])';

卻什么也沒有

好吧,我用這個,它有效

preg_match_all('/(?:\s{1}([+-]{1})\s{1}){0,}'.word.'/', $right, $matches);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM