2016-04-26 50 views
-3

如何使用正則表達式在下面的表達式中忽略abc和def,01。我試過不理我,這是行不通的。如何構造這個正則表達式?

ABC-DEF-SMDP-01去

+1

字符串請仔細閱讀[如何創建一個最小的,完整的,並可驗證示例](http://stackoverflow.com/help/mcve)。然後回來並相應地編輯你的問題。 – Jan

回答

1

的一種方式是將原始字符串分割成前綴,感興趣的部分,和後綴,在此後的詞綴去除不需要的charcters:

$raw = "abc-def-smdp-01"; 

preg_match ("/^(.*)(-smdp-)(.*)$/", $raw, $matches); // separate original string into prefix, trunk, suffix 
$matches[1] = preg_replace ("/[^-]/", "", $matches[1]); // non-'-' characters deleted in prefix 
$matches[3] = preg_replace ("/[^-]/", "", $matches[3]); // non-'-' characters deleted in suffixfix 
$result = $matches[1].$matches[2].$matches[3]; // composing target string 

echo $result; 

在線演示可用here。與此類似

NB

問題可以很容易地使用PHP函數庫,其doc within the online php manual自帶EXAKT語法,示例代碼和用戶註釋的一些知識來解決。

在這種情況下,一看,

當然,對於預期功能找到合適的人選假定至少現有設施敷衍的把握,這使得15分鐘瀏覽hierarchical index明智的投資時間

+0

你能告訴我這個使用正則表達式而不是PHP – chethan

+0

你的編程環境是什麼?爲什麼你用'preg_match'標記你的問題,如果它不是PHP? – collapsar

+0

澄清我以前的評論:純粹的正則表達式用於匹配文本模式_但是,您還想修改需要了解正在使用哪種編程環境的知識。 – collapsar

0

我會用這個模式:

preg_match("/\w+\-\w+\-(\w+)\-\d+/", "Abc-def-smdp-01", $output); 
Echo $output[1]; 

http://www.phpliveregex.com/p/ftB

編輯:或者你需要的破折號?
在這種情況下,你需要使用此模式:"/\w+(\-)\w+(\-)(\w+)(\-)\d+/"
然後輸出爲:
echo $output[1].$output[2].$output[3].$output[4];
或環,並建立與.=