gixxer
gixxer

Reputation: 824

regex to find all the strings between certain patterns

My input string can be one of the following lines:

Active App: Coffee (priority 34)

Active App: Hot Bread (priority 20)

Active App: Hot Baked Bread (priority 1)

etc...

In this case, instead of "Coffee", it could be any string [a-zA-Z] (one or more words).

In "(priority 34)", only the integer would change.

So how do I get the "Coffee"/"Hot Bread"/"Hot Baked Bread" from this line?

I am unable to properly handle the space between the words.

Upvotes: 2

Views: 52

Answers (1)

Andreas Lorenzen
Andreas Lorenzen

Reputation: 4230

Here's a simple solution with python regex match() for you:

It disregards the part of the string after the application name that you want to capture. But that could be added, if important.

It will capture untill it sees a (, and then later strip the trailing whitespace character from the string.

import re;

myStr = "Active App: Hot Baked Bread (priority 34)";
appStr = re.match("Active App: ([^\(]*)", myStr);
print(appStr.group(1).rstrip());

Here's a version that only captures the actual 'Active App' name, without the need to trim the string afterwards. And also checks to see that a match was found before printing it:

import re;

myStr = "Active App: Coffee Some (priority 34)";
appStringMatch = re.match("Active App: (.*)\s\(", myStr);
if appStringMatch:
    print(appStringMatch.group(1));

Upvotes: 2

Related Questions