2013-03-16 16 views
0

我有一些代碼,如:正則表達式:匹配兩個相鄰串

if('hello' == 2 && 'world' !== -1){ 
    return true; 
} 

我有一些麻煩,在if聲明匹配的條件。我想到的第一個正則表達式是/'.*'/,但這種匹配:

  1. '你好'
  2. '== 2 & &'
  3. '世界'

這不是我希望。我只想匹配單引號和裏面的文本。

  1. '你好'
  2. '世界'

任何身體有什麼想法?

+1

PHP不是_regular_語言。使用正則表達式解析它是每個定義的錯誤選擇。 – knittl 2013-03-16 10:05:46

+0

PHP本身有一個標記器:http://stackoverflow.com/questions/5727951/what-are-some-practical-uses-of-php-tokenizer和http://php.net/manual/en/ref。 tokenizer.php。 **用它** – nhahtdh 2013-03-16 12:48:42

回答

0

試試這個

preg_match_all('/\'[^\'\r\n]*\'/m', $subject, $result, PREG_PATTERN_ORDER); 
for ($i = 0; $i < count($result[0]); $i++) { 
    # Matched text = $result[0][$i]; 
} 

說明

" 
'   # Match the character 「'」 literally 
[^'\\r\\n] # Match a single character NOT present in the list below 
       # The character 「'」 
       # A carriage return character 
       # A line feed character 
    *   # Between zero and unlimited times, as many times as possible, giving back as needed (greedy) 
'   # Match the character 「'」 literally 
" 
0

兩個匹配的組詮釋這應該拿起你引用的值:

^.*(\'.*?\').*(\'.*?\').*$ 
0

對於您的具體情況

\'[a-z]*?\' 

對於整個代碼,如果你有引號大寫字符,你可以使用

\'[a-zA-Z]*?\' 

但是,如果你在引號中有特殊字符那麼你可以使用@Chris Cooper建議的內容。根據您的需要,可能會有各種答案。

注意:'?'之後*使*非貪婪,所以它不會嘗試搜索,直到最後的報價。

這也很重要你使用哪種正則表達式來獲得答案。

0

這就是我想出了!

preg_match_all("#'[^'\n\r]*'#", $subject, $matches); 
  1. 比賽'
  2. 匹配任何不是'的字符,新行或回車。
  3. 比賽'

沒有所有的逃避,我認爲它是一個更易讀 - 爲正則表達式,無論如何。