簡體   English   中英

Python - 僅當出現在非大寫單詞之前刪除所有出現的字符

[英]Python - Removing all occurrences of a character only when it appears before non-capitalized words

我有以下字符串:

mystring= "Foo some \n information \n Bar some \n more \n information \n Baz more \n information"

我想只保留“\\n”在以大寫字母開頭的單詞之前。 我想在我的句子中刪除所有其他的“\\n”實例。

期望的輸出:

"Foo some information \n Bar some more information \n Baz more information"

有沒有辦法用 re.sub 做到這一點? 我可以考慮嘗試拆分單詞並使用word[0].isupper()參數。 但是,我相信可能有一種方法可以用正則表達式識別大寫單詞。

您可以使用此否定前瞻正則表達式:

>>> mystring = "Foo some \n information \n Bar some \n more \n information \n Baz more \n information"
>>> print (re.sub(r'\n(?! *[A-Z]) *', '', mystring))
Foo some information
 Bar some more information
 Baz more information

正則表達式詳情:

  • \\n : 匹配換行符
  • (?! *[AZ]) * :否定前瞻斷言我們在可選空格后沒有大寫字母。 之后匹配 0 個或多個空格。

如果文本可能跨越段落(盡管在問題中提到了“句子”),您可以使用正則表達式

 *\n *(?!\n*[A-Z])

(在第一個*之前有一個空格)。

匹配項被替換為一個空格。

演示

這將執行以下操作:

 *            * match 0+ spaces 
\n            * match a newline char
 *            * match 0+ spaces
(?!\n*[A-Z])  * match 0+ newlines followed by an uc letter
              * in a negative lookahead

如鏈接所示,文本

Now is the time for all good regexers
to social distance themselves.
Here's to negative lookbehinds!

And also to positive lookbehinds!

變成

Now is the time for all good regexers to social distance themselves.
Here's to negative lookbehinds!

And also to positive lookbehinds!

即使換行符跟隨negative lookbehinds! 后面不是直接跟一個大寫字母,而是跟在另一個換行符后面跟一個大寫字母。

如果字符串以換行符結尾,它將被刪除。 那是因為我使用的是負面預測而不是正面預測。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM