nubme
nubme

Reputation: 3167

Python: pattern matching for a string

Im trying to check a file line by line for any_string=any_string. It must be that format, no spaces or anything else. The line must contain a string then a "=" and then another string and nothing else. Could someone help me with the syntax in python to find this please? =]

pattern='*\S\=\S*'

I have this, but im pretty sure its wrong haha.

Upvotes: 0

Views: 2557

Answers (5)

Tobias
Tobias

Reputation: 4292

Since Python 2.5 I prefer this to split. If you don't like spaces, just check.

left, _, right = any_string.partition("=")
if right and " " not in any_string:
    # proceed

Also it never hurts to learn regular expressions.

Upvotes: 1

ghostdog74
ghostdog74

Reputation: 342373

Ok, so you want to find anystring=anystring and nothing else. Then no need regex.

>>> s="anystring=anystring"
>>> sp=s.split("=")
>>> if len(sp)==2:
...   print "ok"
...
ok

Upvotes: 1

Michał Niklas
Michał Niklas

Reputation: 54302

Don't know if you are looking for lines with the same value on both = sides. If so then use:

the_same_re = re.compile(r'^(\S+)=(\1)$')

if values can differ then use

the_same_re = re.compile(r'^(\S+)=(\S+)$')

In this regexpes:

  • ^ is the beginning of line
  • $ is the end of line
  • \S+ is one or more non space character
  • \1 is first group

r before regex string means "raw" string so you need not escape backslashes in string.

Upvotes: 4

Eugene
Eugene

Reputation: 1730

I don't know what the tasks you want make use this pattern. Maybe you want parse configuration file. If it is true you may use module ConfigParser.

Upvotes: 1

Amber
Amber

Reputation: 526613

pattern = r'\S+=\S+'

If you want to be able to grab the left and right-hand sides, you could add capture groups:

pattern = r'(\S+)=(\S+)'

If you don't want to allow multiple equals signs in the line (which would do weird things), you could use this:

pattern = r'[^\s=]+=[^\s=]+'

Upvotes: 1

Related Questions