[英]Regex: Extract a part of a string eliminating specific patterns of it
我有以下字符串示例,我只想提取它的中間部分,以消除每個字符串前面和后面的模式:
Exp1: Error: -This can be an example. (YT-0E8)
Error: -This can be an example. (YT-0E8)
Exp1: Warning: -Warning can happen too (WP-003)
Exp3: Error: Error can happen this way as well. (PP-W28)
Error: Error can happen this way as well. (PP-W28)
我只想得到以下輸出:
Ans1: -This can be an example.
Ans2:-警告-Warning can happen too
Ans3: Error can happen this way as well.
如您所見,我試圖消除前面的 FIRST 模式,它可以是Error:
或Warning:
,冒號后面有一個空格,而 SECOND 模式是前面帶有字母數字字符串和空格的括號其中: (TT-T56)
我已經達到了匹配前后模式的程度,但找不到完成它們的方法: ^(Warning: |Error: ).*\((\w+-\d+)\)$
有什么辦法可以解決這個問題?
我會在這里使用正則表達式替換方法:
inp = ["Error: -This can be an example. (YT-0E8)", "Warning: -Warning can happen too (WP-003)", "Error: Error can happen this way as well. (PP-W28)"]
output = [re.sub(r'^\w+:\s*|\s*\(.*?\)$', '', x) for x in inp]
print(output)
# ['-This can be an example.', '-Warning can happen too',
# 'Error can happen this way as well.']
或者,這種方法會剝離前導標簽,后跟冒號或括號中的尾隨項,留下您想要的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.