user2643864
user2643864

Reputation: 651

Regex expression help using Python

My mind is getting a little numb with regex. I need to come up with a regular expression to match any of the following scenarios, but so far I have only come up with the following expression that isn't quite working:

(package)(\.)(path)(\s+)(=)( )(').*?..*?..*?..*?(.).*?(')

I need to build two different expressions.

Expression #1 should match any of the following strings.

package.path = 'any string or path here'
package.path = "any string or path here"
package.path='any string or path here'
package.path="any string or path here"

Expression #2. should match any of the following strings.

package.path = package.path .. 'any string or path here'
package.path = package.path .. "any string or path here"
package.path = package.path..'any string or path here'
package.path = package.path.."any string or path here"
package.path=package.path .. 'any string or path here'
package.path=package.path .. "any string or path here"

I would appreciate any help from a Regex Guru out there.

Thanks.

Upvotes: 0

Views: 52

Answers (3)

njzk2
njzk2

Reputation: 39403

For starters, . is a special char in regex, you'll want to escape it with \.

then, + means one or more. Your spaces are present 0 or 1 times, which is indicated by ?

then, character classes are indicated using [], so your quotes can be classified as ['"]

finally, we can use \1 to recall the matched quote

With that in mind, your first expression is

package\.path\s?=\s?(['"]).*\1

and the second is

package\.path\s?=\s?package\.path\s?\.\.\s?(['"]).*\1

Upvotes: 1

Atri
Atri

Reputation: 5831

Expression #1: package.path\s?=\s?['"][\w\s]+['"]
Expression #2: package.path\s?=\s?package.path\s..\s['"][\w\s]+['"]

Upvotes: 1

alecxe
alecxe

Reputation: 474241

You can use package\.path\s?=\s?(package\.path)?(\s\.\.\s)?('|").*?('|") regex:

import re

data = """package.path = 'any string or path here'
package.path = "any string or path here"
package.path='any string or path here'
package.path="any string or path here"
package.path = package.path .. 'any string or path here'
package.path = package.path .. "any string or path here"
package.path=package.path .. 'any string or path here'
package.path=package.path .. "any string or path here"
"""


pattern = re.compile(r"""package\.path\s?=\s?(package\.path)?(\s\.\.\s)?('|").*?('|")""")
for line in data.splitlines(False):
    match = pattern.match(line)
    print match.group(0) if match else "No match"

Upvotes: 1

Related Questions