views:

60

answers:

5

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.

+1  A: 
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=]+'
Amber
thanks, ya i would probably need to capture it for later use soo.. pattern = r'([^\s=])+=(^\s=]+)'
nubme
+1  A: 

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.

Evgeniy
+3  A: 

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.

Michał Niklas
thanks! defining what each expression does also helped a lot =]
nubme
the code you gave me works, but how do i match exactly one '='? (r'^(\S+)={1}(\S+)$')doesnt seem to work
nubme
Try: `r'^([^=\s]+)=([^=\s]+)$')`, in `[` brackets `^` excludes chars and in this example it excludes `=` and whitespaces (`\s`)
Michał Niklas
thanks =] very nice
nubme
+1  A: 

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
ghostdog74
That will find any line with one "=" in it. Probably need to check that neither of the parts are empty.
neil
+1  A: 

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.

Tobias