Hướng dẫn python regex multiline flag - cờ nhiều dòng regex python

I want to transform chunks of text into a database of single line entries database with regex. But I don't know why the regex group isn't recognized. Maybe because the multiline flag isn't properly set. I am a beginner at python.

import re
with open("a-j-0101.txt", encoding="cp1252") as f: 
    start=1
    ecx=r"(?P[0-9]{1,3}) célébrités ou évènements"
    ec1=""
    nmx=r"(?P.+)\r\nAfficher le.*"
    nm1=""
    for line in f:
        if start == 1:
            out = open('AST0101.txt' + ".txt", "w", encoding="cp1252") #utf8 cp1252
            ec1 = re.search(ecx,line)
            out.write(ec1.group("entrcnt"))
            start=0
        out.write(r"\r\n")
        nm1 = re.search(nmx,line, re.M)
        out.write(str(nm1.group("ename")).rstrip('\r\n'))
    out.close()

But I get the error:

File "C:\work-python\transform-asth-b.py", line 16, in 
  out.write(str(nm1.group("ename")).rstrip('\r\n'))

builtins.AttributeError: 'NoneType' object has no attribute 'group'

here is the input:

210 célébrités ou évènements ont été trouvés pour la date du 1er janvier.
Création de l'euro
Afficher le...
...
...
...

expected output:

210
Création de l'euro ;...
... ;...
... ;...

EDIT: I try to change nmx to match \n or \r\n but no result:

nmx=r"(?P.+)(\n|\r\n)Afficher le"

best regards

Hướng dẫn python regex multiline flag - cờ nhiều dòng regex python

Đã đăng vào thg 11 27, 2017 9:57 SA 3 phút đọc 3 phút đọc

1. Regex là gì?

Regular expression (Regex) là một chuỗi miêu tả một bộ các chuỗi khác, theo những quy tắc cú pháp nhất định. Bạn cũng có thể gọi Regex là một ngôn ngữ. Và hầu như ngôn ngữ lập trình nào cũng hỗ trợ Regular expression.

2. Regex trong Python.

Regular Expression trong Python được thể hiện qua module re, re Module cung cấp sự hỗ trợ đầy đủ các Regular Expression trong Python. Module này tạo Exception là re.error nếu xảy ra một lỗi trong khi biên dịch hoặc khi sử dụng một Regular Expression. Để sử dụng re việc đầu tiên bạn cần phải import module re vào chương trình, sử dụng với cú pháp như sau:

import re

3. Sử dụng Regex với search(), match(), split()

3.1 re.match()

re.match(pattern, string, flags=0)

So khớp pattern với string với các flag tùy ý. Dưới đây là cú pháp cho hàm này.

Chi tiết về tham số:

pattern : Đây là chuỗn cần so khớp.
string : Đây là chuỗi để tìm kiếm pattern cón tồn tại trong đó không.
flags : Bạn có thể xác định các flag khác nhau bởi sử dụng toán tử |. Các modifier này sẽ được liệt kê ở bảng bên dưới.

Hàm re.match trả về một đối tượng match nếu thành công và trả về None nếu thất bại. Chúng ta sử dụng hàm group(num) hoặc groups() của đối tượng match để lấy biểu thức đã được so khớp (kết nối).

>>> m = re.match(r"(?P\w+) (?P\w+)", "Malcolm Reynolds")
>>> m.group('first_name')
'Malcolm'
>>> m.group('last_name')
'Reynolds'
re.search(pattern, string, flags=0)

Phương thức này thực hiện tìm kiếm chuỗi so khớp trên string và nó sẽ trả về các giá trị được so khớp.

Trong đó:

File "C:\work-python\transform-asth-b.py", line 16, in 
  out.write(str(nm1.group("ename")).rstrip('\r\n'))

builtins.AttributeError: 'NoneType' object has no attribute 'group'
0
File "C:\work-python\transform-asth-b.py", line 16, in 
  out.write(str(nm1.group("ename")).rstrip('\r\n'))

builtins.AttributeError: 'NoneType' object has no attribute 'group'
1

3.4 re.split()

File "C:\work-python\transform-asth-b.py", line 16, in 
  out.write(str(nm1.group("ename")).rstrip('\r\n'))

builtins.AttributeError: 'NoneType' object has no attribute 'group'
2

Trong đó:

File "C:\work-python\transform-asth-b.py", line 16, in 
  out.write(str(nm1.group("ename")).rstrip('\r\n'))

builtins.AttributeError: 'NoneType' object has no attribute 'group'
3
File "C:\work-python\transform-asth-b.py", line 16, in 
  out.write(str(nm1.group("ename")).rstrip('\r\n'))

builtins.AttributeError: 'NoneType' object has no attribute 'group'
4

3.4 re.split()

3.3 Một số flag hay dùng trong Regular Expression

I hay IGNORECASE - Không phân biệt hoa thường khi tiến hành search hoặc match L hay LOCALE - So Khớp với local hiện tại. M hay MULTILINE - Thay đổi $ và ^ thành kết thúc của một dòng và bắt đầu của một dòng thay vì mặc định là kết thúc chuỗi và bắt đầu chuỗi. A hay ACSII - Thay đổi \w, \W, \b, \B, \d, \D, \S và \s thành so khơp full unicode. S hay DOTALL -Thay đổi pattern . thành khớp với bất kỳ ký tự nào và dòng mới. ...

4. Kết Luận

Regular Expression trong python còn rất nhiều nhưng trong bài này mình chỉ hướng dẫn các bạn sử dụng một số regex hay dùng trong python mong rằng nó giúp ích được các bạn.

All rights reserved