Python: How to use RegEx in an if statement?

后端 未结 5 2077
鱼传尺愫
鱼传尺愫 2020-12-25 10:06

I have the following code which looks through the files in one directory and copies files that contain a certain string into another directory, but I am trying to use Regula

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-25 10:35

    if re.search(r'pattern', string):

    Simple if-test:

    if re.search(r'ing\b', "seeking a great perhaps"):     # any words end with ing?
        print("yes")
    

    Pattern check, extract a substring, case insensitive:

    match_object = re.search(r'^OUGHT (.*) BE$', "ought to be", flags=re.IGNORECASE)
    if match_object:
        assert "to" == match_object.group(1)     # what's between ought and be?
    

    Notes:

    • Use re.search() not re.match. Match restricts to the start of strings, a confusing convention if you ask me. If you do want a string-starting match, use caret or \A instead, re.search(r'^...', ...)

    • Use raw string syntax r'pattern' for the first parameter. Otherwise you would need to double up backslashes, as in re.search('ing\\b', ...)

    • In this example, \b is a special sequence meaning word-boundary in regex. Not to be confused with backspace.

    • re.search() returns None if it doesn't find anything, which is always falsy.

    • re.search() returns a Match object if it finds anything, which is always truthy.

    • a group is what matched inside parentheses

    • group numbering starts at 1

    • Specs

    • Tutorial

提交回复
热议问题