![](/img/trans.png)
[英]How to get all the text before and after some characters using regular expressions
[英]How to hide text after matching and before keyword in regular expressions?
我想匹配所有用戶評論,直到KEYWORD。 我也想在關鍵字之前的最后評論之后跳過不重要的可變文本。
import re`
string = '''
COMMENTS:
first comment /user_x
second comment
two lines /user_y
Here is some unimportant text.
KEYWORD:
Don't match comments or anything else after first keyword like this /user_x
KEYWORD: <- again
Also ignore same keyword which could appear serveral times.
'''
我的結果不會跳過不重要的文本。
pattern = re.compile(r'(?<=COMMENTS:)(.+?/(user_x|user_y))+?(?:.+?)(?=KEYWORD:)', flags=re.DOTALL)
match = re.search(pattern, string).group(0)
print(match)
我想要以下輸出:
first comment /user_x
second comment
in two lines /user_y
我究竟做錯了什么? 非常感謝
您可以使用
pattern = re.compile(r'COMMENTS:\s*((?:(?:(?!KEYWORD:).)+?/(?:user_x|user_y))+).+?KEYWORD:', flags=re.DOTALL)
match = re.search(pattern, s)
if match:
print(match.group(1))
輸出不再包含無關行:
first comment /user_x
second comment
two lines /user_y
參見Python演示
細節
COMMENTS:
-文字子串 \\s*
-0+空格 ((?:(?:(?!KEYWORD:).)+?/(?:user_x|user_y))+)
-捕獲組1(如果存在匹配項, match.group(1)
將保留此值):一個或多個重復
(?:(?!KEYWORD:).)+?
-任何不會啟動KEYWORD:
char序列的char,一個或多個但盡可能少 /
-一/
炭 (?:user_x|user_y)
- user_x
或user_x
.+?KEYWORD:
-一個KEYWORD:
任意1個或多個字符后,應盡可能少。 參見regex演示 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.