簡體   English   中英

給定字符串的開始和結束部分時,如何使用正則表達式提取字符串的一部分

[英]How to extract a part of a string using regex, when starting and ending portion of the string is given

我正在編寫一個結構腳本來更改nodejs版本。 為此,我需要刪除

節點-v0.10.32-linux-x64

並替換為

節點-v6.9.1-linux-x64

反之亦然。

下面是該行,我需要一個正則表達式來獲取該行的粗體部分

/ home / portweb / software / nodejs / node-v0.10.32-linux-x64 / bin

以下是更改nodejs版本的代碼。

@task
def changeVersion(appname='nodejs', rootdir='/home/portweb/software',homedir='/home/portweb',tarfile='node-v6.9.1-linux-x64.tar.gz',nodeversion='node-v'):
    """install nodejs"""

    base_dir = rootdir +'/'+appname


    run ('if [ ! -d ' + base_dir + ' ] ; then mkdir -p ' + base_dir + '; fi')

    put('../package/'+tarfile, base_dir + '/', use_sudo=False)

    with cd (base_dir):
        run('tar -zxf '+ tarfile)


    run ('sed -i \'s/regex/'+nodeversion+'/g\' /home/portweb/.bashrc')

    print "****Nodejs Version Changed"

nodeversion = node-v0.10.32-linux-x64node-v6.9.1-linux-x64 ;

這是sed的正則表達式:

"sed -i 's,/home/portweb/software/nodejs/\(.*\)/bin,/home/portweb/software/nodejs/'" + nodeversion + "'/bin,g'"

請注意,您可以使用/以外的其他分隔符,以便於閱讀,因此在這里我們使用,

您可以使用fabric sed函數在prueba.txt中替換所需的鏈:

def sed_node():
    sed('/home/user/test/prueba.txt', 'node-v0.10.32-linux-x64', 'node-v6.9.1-linux-x64')

並運行:

$ fab sed_node

暫無
暫無

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

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