2016-06-28 28 views
3

我一直在閱讀,搜索和試用不同的方式來寫正則表達式,如p {L},[az]和\ w但我似乎無法得到結果我在之後。正則表達式的單詞連接字符和下劃線同時保持標點符號

問題

我做了充分的句子,標點符號,這我通過陣列使用以下pre_match,它在保持詞和標點符號行之有效解析的數組。

preg_match_all('/(\w+|[.;?!,:])/', $match, $matches)

不過,我現在有這樣的話:

  • 字另一個字
  • more_words_like_these

,我希望能夠保持完整性(連接)這些詞,但我目前的preg_match將它們分解成單獨的單詞。

我試過

preg_match_all('/(p{L}-p{L}+|[.;?!,:])/', $match, $matches) 

和;

preg_match_all('/((?i)^[\p{L}0-9_-]+|[.;?!,:])/', $match, $matches) 

,我從here

發現,但不能得到實現這一理想的結果:

Array ([0] A, [1] word, [2] like_this, [3] connected, [4] ; ,[5] with-relevant-punctuation) 

理想我想能也佔了特殊字符作爲其中的一些話可能有口音

+0

你試過'[\ W上。 ;,:?!] +'? – ClasG

+0

它輸入'一個like_this連接;與相關標點符號「或」一個詞like_this連接;與相關標點符號(注意';'之前的空格)? –

+0

......或甚至'\ S'可以做到這一點 - 'preg_match_all('/(\ S +)/',$ match,$ matches)' – ClasG

回答

3

只需將連字符插入字符類。但請注意,連字符需要出現在字符集的開頭或結尾。否則,它將被視爲範圍符號。

(\w+|[-.;?!,:]) 

Regular expression visualization

例子

現場演示

https://regex101.com/r/yI3tM4/2

示例文字

However, I now have words like these: 

Word-another-word 
more_words_like_these 

and I would like to be able to retain the integrity of these words as they are (connected) but my current preg_match breaks them down into individual words. 

樣品匹配

其他的字作爲前拍攝,但連字符的話也被捕獲

Omitted Match 1-9 for brevity 

MATCH 10 
1. [39-56] `Word-another-word` 

MATCH 11 
1. [57-78] `more_words_like_these` 

Omitted Match 12+ for brevity 

說明

NODE      EXPLANATION 
---------------------------------------------------------------------- 
    (      group and capture to \1: 
---------------------------------------------------------------------- 
    \w+      word characters (a-z, A-Z, 0-9, _) (1 or 
          more times (matching the most amount 
          possible)) 
---------------------------------------------------------------------- 
    |      OR 
---------------------------------------------------------------------- 
    [-.;?!,:]    any character of: '-', '.', ';', '?', 
          '!', ',', ':' 
---------------------------------------------------------------------- 
)      end of \1 
---------------------------------------------------------------------- 
+1

謝謝你的答案,並花時間解釋它;很有用。有效 – Jacob

相關問題