![](/img/trans.png)
[英]search substring + integer from a string in python using regular expression
[英]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]
細節
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.