簡體   English   中英

從字符串中獲取子字符串的正則表達式

[英]Regular expression to get substring from a string

考慮我有一個字符串如下,

\n this is a paragraph. please ignore  \n this is a only for testing. please ignore \n

我有一個搜索詞"only for testing" 並且我想在搜索詞所在的\\n獲取包含"only for testing"的句子。 在這種情況下,輸出將this is a only for testing. please ignore this is a only for testing. please ignore

如果我給paragraph作為搜索詞,我應該得到輸出

this is a paragraph. please ignore

我試過了

test_str = "\\n this is a paragraph. please ignore  \\n this is a only for testing. please ignore \\n"
pattern = re.compile("\\\\n(.+?)\\\\n")
match = pattern.findall(test_str)

但沒有按預期工作

您可以使用沒有正則表達式的解決方案:

result = [sent for sent in test_str.split("\\n") if 'only for testing' in sent]

查看Python 演示

細節

  • test_str.split("\\\\n") - 按\\n分割文本
  • if 'only for testing' in sent - 僅保留包含only for testing的項目(對於不區分大小寫的比較, if 'only for testing' in sent.lower()使用if 'only for testing' in sent.lower()

暫無
暫無

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

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