![](/img/trans.png)
[英]In Python, how to write a regular expression matching strings starting with string A but NOT ending with B
[英]How to get multiple strings of starting with a string and ending with string in regular expression module of python?
我想要的是:
假設我使用 OR 運算符將兩個字符串賦予一個變量。 喜歡:
command = 'windows go to books in d drive' or 'windows open books folder in d drive' or 'windows go to books which is in d drive'
我想從這里得到一個詞,即使用 python 中的正則表達式模塊從任何三個字符串中獲取“書籍”。
我試過的:
import re
import os
command = 'windows go to books in d drive' or 'windows open books folder in d drive' or 'windows go to books which is in d drive'
if 'windows go to' or 'windows open' in command:
non_greedy0 = re.compile(r'([go to ](.*?)[ in])|([go to ](.*?)[ folder])')
output0 = non_greedy0.findall(command)
print(output0)
tuple0 =output0[0]
print(tuple0)
subfolder = tuple0[0]
print(subfolder)
foo = 'D' + ':/' + str(subfolder)
os.startfile(foo)
Output:
[('ows ', 'ws', '', ''), ('go ', 'o', '', ''), ('to ', 'o', '', ''), ('ooks ', 'oks', '', ''), (' d ', 'd', '', '')]
('ows ', 'ws', '', '')
ows
File "***", line **, in <module> os.startfile(foo)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'D:/ows '
import re
import os
from random import choice
command = choice(['windows go to books in d drive',
'windows open books folder in d drive',
'windows go to books which is in d drive'])
if 'windows go to' or 'windows open' in command:
non_greedy0 = re.compile('go to (.*?) (which is ){0,1}in')
non_greedy1 = re.compile('go to (.*?) folder')
non_greedy2 = re.compile('open (.*?) folder')
output0 = non_greedy0.findall(command)
output1 = non_greedy1.findall(command)
output2 = non_greedy2.findall(command)
print(output0, output1, output2)
if output0 != []:
tuple0 = output0[0]
elif output1 != []:
tuple0 = output1[0]
elif output2 != []:
tuple0 = output2[0]
print(tuple0)
subfolder = ''.join(tuple0)
print(subfolder)
foo = 'D:\\' + subfolder
os.startfile(foo)
我更改了一些代碼:
or
沒有這樣使用。 or
不隨機選擇; 它選擇第一個不為空的字符串。 random.choice
隨機選擇。[]
表示“組中的任何字符”,這不是您想要的:您想要完全匹配。 而且你的正則表達式不匹配'windows open...'''.join(tuple0)
。 那是因為tuple0
的長度為 3(因為正則表達式中有 3 對括號),並且 2 項必須是空字符串。 ''.join
通過連接三個字符串來解決問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.