如何只获得Python中匹配的文本?

时间:2013-02-18 13:00:07

标签: python regex

我在Python中有以下代码

import psutil
import re

_list = psutil.get_pid_list()

for i in _list:
    if i > 0:
        _process_path = psutil.Process(i).exe
        _match = re.search('\/Applications\/.*\.app\/',_process_path)
        if _match:
            print _process_path

它有效,这是它返回的一个例子:

/Applications/RegExr.app/Contents/MacOS/RegExr
/Applications/Google Chrome.app/Contents/Versions/24.0.1312.57/Google Chrome Helper.app/Contents/MacOS/Google Chrome Helper
/Applications/TextWrangler.app/Contents/Helpers/Crash Reporter.app/Contents/Helpers/crash-catcher
/Applications/TextWrangler.app/Contents/MacOS/TextWrangler
/Applications/Google Chrome.app/Contents/MacOS/Google Chrome
/Applications/Utilities/Activity Monitor.app/Contents/MacOS/Activity Monitor
/Applications/AppCleaner.app/Contents/Library/LoginItems/AppCleaner Helper.app/Contents/MacOS/AppCleaner Helper
/Applications/Transmit.app/Contents/MacOS/TransmitMenu.app/Contents/MacOS/TransmitMenu
/Applications/Twitter.app/Contents/MacOS/Twitter
/Applications/ScreenFlow.app/Contents/MacOS/ScreenFlowHelper.app/Contents/MacOS/ScreenFlowHelper

如何制作它以便它只返回它?

/Applications/RegExr.app
/Applications/Google Chrome.app
/Applications/TextWrangler.app/Contents/Helpers/Crash Reporter.app
/Applications/TextWrangler.app
/Applications/Google Chrome.app
/Applications/Utilities/Activity Monitor.app
/Applications/AppCleaner.app
/Applications/Transmit.app
/Applications/Twitter.app
/Applications/ScreenFlow.app

2 个答案:

答案 0 :(得分:3)

使用MatchObject.group() method

打印匹配的组
print _match.group()

答案 1 :(得分:3)

您的_match对象可以将匹配的文本作为_match.group(0)返回。

相关问题