开发者

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 ano开发者_StackOverflow社区ther 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.


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.


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=]+'


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜