2016-02-16 16 views
2

你好,這是我的字符串不要在正則表達式獲取字符串中的描述內容

 
/* 
anything description 
*/ 

Data1 = value1; 

Other_Data = Other_Value; 

/* 
my other description 
*/ 

Anything = Any_Answer; 

/* 

this is description and must not detect 

Description_Data = Any_Value; 

*/ 

現在我想用正則表達式,並得到這樣的

 
Data1 
Other_Data 
Anything 

 
value1 
Other_Value 
Any_Answer 

在數組中,但我不想要正則表達式檢測任何內部(描述框)

/* */

Description_Data = Any_Value;

這是我的正則表達式

\h*(.*?)\h*[=]\h*(.*?)\h*[;]

我的問題是,正則表達式得到即使在說明書和一些按鍵所有的按鍵和值,鍵之前像所有的描述鍵之前得到的一切......我想就這樣

 
Data1 
Other_Data 
Anything 

 
value1 
Other_Value 
Any_Answer 

有什麼問題?

+0

鍵和值只包含字母數字和下劃線嗎? –

+1

請分享你的嘗試。 –

+0

用我的正則表達式更新 – MyJustWorking

回答

2

我假設鍵和值只包含字母數字和下劃線。

您可以跳過描述與SKIP-FAIL PCRE construct,僅匹配在一行的開頭

(?m)\/\*[^*]*\*+([^\/*][^*]*\*+)*\/(*SKIP)(*F)|^\s*(\w+)\s*=\s*(\w+) 

的key = value對見regex demo

正則表達式匹配:

  • \/\*[^*]*\*+([^\/*][^*]*\*+)*\/(*SKIP)(*F) - 匹配一個多行註釋(這個模式是用unroll-the-loop techique,是相當有效),並使得正則表達式引擎放棄匹配的文本和索引移動到這個匹配文本(從而結束時,我們忽略了描述)
  • | - 或...
  • ^\s*(\w+)\s*=\s*(\w+) - ^比賽然後我們匹配捕獲到組1(密鑰)一個或多個單詞字符(與(\w+)),然後只匹配零個或多個空格(\s*),接着是=,同樣零個或多個空格然後我們捕獲到組2()一個或多個單詞字符。

(?sm)是內聯修飾符,您可以將它們寫爲'~pattern-here~sm'sDOTALL修飾符使.匹配換行符。該mMULTILINE修改使得^$比賽一的開頭和結尾,而不是整個字符串。

一種用於當鍵和值可以由任何字符和值尾隨邊界更復雜的情況下的變化是字符串的; +換行符/端:

(?sm)\/\*[^*]*\*+(?:[^\/*][^*]*\*+)*\/(*SKIP)(*F)|^\s*([^=\n]+?)\s*=\s*(.*?);\h*(?:$|\r?\n) 

參見another demo

IDEONE demo

$re = '~/\*[^*]*\*+(?:[^/*][^*]*\*+)*/(*SKIP)(*F)|^\s*([^=\n]+?)\s*=\s*(.*?);\h*(?:$|\r?\n)~sm'; 
$str = "/*\nanything description\n*/\n\nData1 = value1;\n\nOtherData<> = Other Value;\n\n/*\nmy other description\n*/\n\nAny thing = Any \nAnswer;\n\n/*\n\nthis is description and must not detect\n\nDescription_Data = Any_Value;\n\n*/"; 
preg_match_all($re, $str, $matches); 
print_r($matches[1]); 
print_r($matches[2]); 

輸出:

Array 
(
    [0] => Data1 
    [1] => OtherData<> 
    [2] => Any thing 
) 
Array 
(
    [0] => value1 
    [1] => Other Value 
    [2] => Any 
Answer 
) 

要還忽略全單行註釋(從#;//行),您還可以加入^\h*(?:\/\/|[#;])[^\n]*替代SKIP-FAIL部分:

(?sm)(?:^\h*(?:\/\/|[#;])[^\n]*|\/\*[^*]*\*+(?:[^\/*][^*]*\*+)*\/)(*SKIP)(*F)|^\s*([^=\n]+?)\s*=\s*(.*?);\h*(?:$|\r?\n) 

見尚未another regex demo。該^\h*(?:\/\/|[#;])[^\n]*行的開頭匹配(與^),那麼無論是//#;,然後比換行(添加\r如果你有的Mac OS行尾)等零個或多個字符。

+0

你能解釋更簡單嗎? – MyJustWorking

+0

正則表達式會跳過所有的'/ * ... * /',只能將鍵和值分別抓取到組1和2中。 :) –

+0

你能告訴我我應該怎麼做#和/和; (其他描述詞)在一行中? – MyJustWorking