Propeller
Propeller

Reputation: 2533

How to get only the matched text in Python?

I have the following code in 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

It works and here is an example of what it returns:

/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

How do I make it so that it only returns this instead?

/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

Upvotes: 0

Views: 98

Answers (2)

wRAR
wRAR

Reputation: 25569

Your _match object can return the matched text as _match.group(0).

Upvotes: 4

Martijn Pieters
Martijn Pieters

Reputation: 1124758

Print the matched group instead, using the MatchObject.group() method:

print _match.group()

Upvotes: 3

Related Questions