簡體   English   中英

如何在python的正則表達式模塊中獲取多個以字符串開頭和以字符串結尾的字符串?

[英]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)

我更改了一些代碼:

  1. 在Python中, or沒有這樣使用。 or隨機選擇; 它選擇第一個不為空的字符串。 random.choice隨機選擇。
  2. 您使用的正則表達式。 正則表達式中的[]表示“組中的任何字符”,這不是您想要的:您想要完全匹配。 而且你的正則表達式不匹配'windows open...'
  3. 我使用了三個正則表達式而不是一個。 這使得代碼更容易理解。 (並且更容易調試!)
  4. 要查找子文件夾名稱,我使用了''.join(tuple0) 那是因為tuple0的長度為 3(因為正則表達式中有 3 對括號),並且 2 項必須是空字符串。 ''.join通過連接三個字符串來解決問題。
  5. 在 Windows 中,使用反斜杠代替正斜杠作為路徑分隔符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM