[英]Regular expression pattern (match newline and tab) in Python
我正在使用 Python。 请帮我找到正则表达式模式:
SELECT
SELECT select1
FROM
SELECT A
FROM B
WHERE C
WHERE X
FROM
SELECT from1
FROM from2
WHERE from3
WHERE
SELECT child1
FROM child2
我想取出三个部分:
SELECT select1
FROM
SELECT A
FROM B
WHERE C
WHERE X
和
SELECT from1
FROM from2
WHERE from3
和
SELECT child1
FROM child2
对于我取出的每个部分,我将进行递归调用以再次执行相同的操作。 :)
这个正则表达式对你有用
(?=\t)((?:.|\n\t+)*)
正则表达式分解
(?=\t) #This lookahead finds the position of \t
( #Capturing group
(?: #Non-capturing group
. #Match any character (but this does not matches \n.So we use alternation)
| #Alternation (OR)
\n\t+ #Match all lines \n followed by \t (as it seems from your input)
)* #Repeat this until any of the condition (mainly \n followed by \t) fails
)
注意:- 在 python 中使用它时,请确保它只是\\t
而不是简单的空间。
Python代码
p = re.compile(r'(?=\t)((?:.|\n\t+)*)', re.MULTILINE)
test_str = "SELECT\n\tSELECT select1\n\tFROM\n\t\tSELECT A\n\t\tFROM B\n\t\tWHERE C\n\tWHERE X\nFROM\n\tSELECT from1\n\tFROM from2\n\tWHERE from3\nWHERE\n\tSELECT child1\n\tFROM child2"
print(re.findall(p, test_str))
超级简单: ^\\s(.*)
下面是如何在代码中使用它:
import re
str = "Your text here"
p = re.compile(ur'^\s(.*), re.MULTILINE)
re.findall(p, str)
^
锚定到行开始\\s
匹配一个空格(.*)
匹配所有内容直到行尾
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.