0

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.

2
  • How do you intend to use that pattern? Commented Oct 21, 2010 at 6:46
  • 1
    Also, I think this is more of a regex question than a Python question. Just saying! Commented Oct 21, 2010 at 6:47

5 Answers 5

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks! defining what each expression does also helped a lot =]
the code you gave me works, but how do i match exactly one '='? (r'^(\S+)={1}(\S+)$') doesnt seem to work
Try: r'^([^=\s]+)=([^=\s]+)$'), in [ brackets ^ excludes chars and in this example it excludes = and whitespaces (\s)
1
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=]+'

1 Comment

thanks, ya i would probably need to capture it for later use soo.. pattern = r'([^\s=])+=(^\s=]+)'
1

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.

Comments

1

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

1 Comment

That will find any line with one "=" in it. Probably need to check that neither of the parts are empty.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.