[英]Get a string between two variable strings that contain regex specific characters using python
[英]How to get string between two strings using regex in Python
我有兩個輸入字符串
s1 = "ABCDhelloXYZ"
s2 = "DEFwelcomeXYZ"
我想從 s1 得到“你好”,從 s2 得到“歡迎”。 輸入字符串的開頭可以是“ABCD”或“DEF”。 結尾永遠是“XYZ”。
我嘗試使用 re.search 並且我能夠通過使用 2 個不同的正則表達式來獲得所需的 output
re.search(r'ABCD(.*?)XYZ')
和
re.search(r'DEF(.*?)XYZ')
但是如何使用單個正則表達式獲得 output,它適用於 s1 或 s2? 我試過了
re.search(r'((ABCD)|(DEF))(.*?)XYZ'`)
但它給出了不同的 output。
我會使用非捕獲組,例如:
^(?:ABCD|DEF)(.*?)XYZ$
(?:...)
是一個非捕獲組。 基本上,您是在說“我對價值不感興趣”。
正如 S3DEV 所指出的,如果您捕獲的文本總是小寫,您應該避免使用相當模糊.*?
並將其替換為[az]+
。
pipe |
字符是or
運算符,這意味着字符串將以ABCD
或DEF
開頭。
import re
resp = 'my data to look in for the regex <identifier-word-or-character>123abc</identifier-word-or-character>'
pattern = r"<identifier-word-or-character>(.*?)</identifier-word-or-character>"
resp = re.findall(pattern, resp, flags=0)
print(resp)
(它將打印 123abc 因為那是之間的文本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.