Ben Chuanlong Du's Blog

It is never too late to learn.

Make A Dot Match Newline in the re Module in Python

Comment

  1. Pass re.DOTALL to the option flags to make a dot match newlines as well.
In [2]:
import re
In [5]:
pattern = ".*select\s+.*\s+from\s+(\w+\.?\w+)\s+"
sql = """
    select
       c1, 
       c2,
    from
        abc.table
    where
        1 = 1
    """.strip().lower()
re.search(pattern, sql)
In [7]:
pattern = ".*select\s+.*\s+from\s+(\w+\.?\w+)\s+"
sql = """
    select
       c1, 
       c2
    from
        db.table
    where
        1 = 1
    """.strip().lower()
match = re.search(pattern, sql, re.DOTALL)
print(match.group(0))
print(match.group(1))
select
       c1, 
       c2
    from
        db.table
    
db.table
In [8]:
pattern = ".*select\s+.*\s+from\s+(\w+\.?\w+)\s+"
sql = """
    select
        count(*) as total,
        count(case
                when item_site_id = 15 then 1
                else 0
            end) as total_au
    from
        db.table
    """
match = re.search(pattern, sql, re.DOTALL)
print(match.group(0))
print(match.group(1))
    select
        count(*) as total,
        count(case
                when item_site_id = 15 then 1
                else 0
            end) as total_au
    from
        db.table
    
db.table
In [9]:
"abc".split(", ")
Out[9]:
['abc']
In [10]:
(x,) = ["nima"]
In [12]:
x, *_ = ["nima"]
In [13]:
x
Out[13]:
'nima'

Comments