[英]RegEx Split - keeping the punctuations
我有一句話看起來像這樣:
"what is this? i want this to work. blah"
如何獲得包含標點符號的數組,如下所示?
[0] = what is this?
[1] = i want this to work.
[2] = blah
用您的示例文本分割為(?<=[.?!])\\s*
。
除此之外,我想補充一點,使用正則表達式將文本可靠地拆分成句子是不可能的。
您可以使用Regex.Split
來匹配帶標點符號的空白。
Regex.Split(input, "(?<=[.?!])\s+");
(?<=)
是一個后向組。 它檢查匹配是否在組之前,但不捕獲它。
您將需要執行子字符串替換的方法。 例如,使用Ruby的gsub
:
"I am a lion. Hear me roar! Where is my cub? Never mind, found him.".gsub(/[.?!]/, '\0|').split('|')
=> ["I am a lion.", " Hear me roar!", " Where is my cub?", " Never mind, found him."]
假設句子的定義以結尾.
, ?
或!
當然。 省略號( ...
)會將其擰緊一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.