[英]How to find a pattern have word and non-word characters after a words combo and before next space using regex
輸入文本
str_ = '''abc xyz pq m_www.google.in_10 -name itel.google.in
abc xyz pq I_www.google.in_9 -name itel.google.com
abc xyz pq I_www.google.in_8
abc xyz pq I.www_google.com_10 -name itel_google.com_9'''
需要提取 'abc xyz pq ' 之后的組合直到下一個空格。 這個組合可以包含 \w & dot。 還想提取'-name'之后的組合。 這2個組合應該是一個列表
預期 output(作為列表)
'[['m_www.google.in_10', 'itel.google.in']
['I_www.google.in_9', 'itel.google.com']
['I_www.google.in_8', '']
['I_www.google.com_10', 'itel.google.com_9']]'
我的偽代碼
import re
re.findall(r'abc xyz pq (\w+)\.(\w+)\.(\w+) -name? (\w+?)\.(\w+?)\.(\w+?)',str_ )
您可以在re.findall
中使用此正則表達式:
>>> for i in re.findall(r'abc xyz pq\s+([\w.]+)(?:\s+-name\s+([\w.]+))?', str_):
... print (i)
...
('m_www.google.in_10', 'itel.google.in')
('I_www.google.in_9', 'itel.google.com')
('I_www.google.in_8', '')
('I.www_google.com_10', 'itel_google.com_9')
請注意,該列表與您預期的數據結構不匹配,但您可以迭代此列表並創建您的自定義結構。
或者,您可以使用re.finditer
並准備您的自定義列表。
使用特定的正則表達式模式:
import re
s = '''abc xyz pq m_www.google.in_10 -name itel.google.in
abc xyz pq I_www.google.in_9 -name itel.google.com
abc xyz pq I_www.google.in_8
abc xyz pq I.www_google.com_10 -name itel_google.com_9'''
res = list(map(list, re.findall(r'\babc xyz pq (\w+[.\w]+)(?: -name (\w+[.\w]+))?', s)))
pprint(res)
預期的 output(列表列表):
[['m_www.google.in_10', 'itel.google.in'],
['I_www.google.in_9', 'itel.google.com'],
['I_www.google.in_8', ''],
['I.www_google.com_10', 'itel_google.com_9']]
正則表達式模式詳細信息:
\b
- 單詞邊界
(\w+[.\w]+)
- 捕獲單詞字符\w+
后跟.
char 或 word 字符序列[.\w]+
(?: ...)
- 將組標記為非捕獲,盡管在上述情況下它包含另一個捕獲的組(內部組)(...)?
- 將組標記為可選( ?
量詞匹配零到一次)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.