[英]Regex to find substring starting with [ ]
下面是我獲得的更大字符串(detaildesc_final)中存在的示例子字符串。 我需要對字符串使用正則表達式搜索,以便可以從[Data]部分檢索所有以“ []”(我的意思是兩個方括號)開頭的行。 在[Data]部分中應檢索所有行,直到遇到[Logs]行。
[Data]
[] some text
[] some_other_text
[] some_other_text
[] some_other_text
[] some_other_text
[] some_other_text
[] some_other_text
[] some_other_text
[] some_other_text
[] some_other_text
[] some_other_text
[] some_other_text
[Logs]
我正在使用Python處理代碼,並且使用了以下命令(這顯然是不正確的)。
re.findall(r'\b\\[\\]\w*', detaildesc_final)
我需要結果采用以下格式:
some text
some_other_text
some_other_text
some_other_text
some_other_text
some_other_text
some_other_text
some_other_text
some_other_text
some_other_text
some_other_text
some_other_text
我已經在網上看到了很多東西,因此可以找出以單個雙字符而不是兩個(在這種情況下為[])開頭的任何行。 任何幫助將不勝感激。 謝謝。
不要使事情過於復雜。
for line in detaildesc_final.split('\n'):
if line.startswith('[]'):
do_something()
import re
str = """
[Data]
[] some text
[] some_other_text
[] some_other_text
[] some_other_text
[] some_other_text
[] some_other_text
[] some_other_text
[] some_other_text
[] some_other_text
[] some_other_text
[] some_other_text
[] some_other_text
[Logs]
"""
print re.sub("([[a-zA-Z ]{0,}][ ]?)", '',str)
輸出:
some text
some_other_text
some_other_text
some_other_text
some_other_text
some_other_text
some_other_text
some_other_text
some_other_text
some_other_text
some_other_text
some_other_text
您需要正面評價:
import re
pattern=r'(?<=\[\])(.\w.+)'
string_1="""[Data]
[] some text
[] some_other_text
[] some_other_text
[] some_other_text
[] some_other_text
[] some_other_text
[] some_other_text
[] some_other_text
[] some_other_text
[] some_other_text
[] some_other_text
[] some_other_text
[Logs]"""
match=re.finditer(pattern,string_1,re.M)
for item in match:
print(item.group(1))
輸出:
some text
some_other_text
some_other_text
some_other_text
some_other_text
some_other_text
some_other_text
some_other_text
some_other_text
some_other_text
some_other_text
some_other_text
正則表達式說明:
Positive Lookbehind (?<=\[\])
它告訴正則表達式引擎暫時向后退字符串,以檢查后面的內部文本是否可以匹配。
\\[
匹配字符[
從字面上(區分大小寫) \\]
從字面上匹配字符]
(區分大小寫) .
匹配任何字符(行終止符除外) \\w
匹配任何單詞字符(等於[a-zA-Z0-9_]
) +
量詞—
匹配一次和無限次,盡可能多地匹配,並根據需要返回(貪婪) import re
re.findall(r'\[\] (.*)\n\n', detaildesc_final)
輸出:
['some text',
'some_other_text',
'some_other_text',
'some_other_text',
'some_other_text',
'some_other_text',
'some_other_text',
'some_other_text',
'some_other_text',
'some_other_text',
'some_other_text',
'some_other_text']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.