我正在尝试获取与特定字符串匹配的行之间的所有行,直到出现结束行。起始模式和结束模式可以在同一文件中的不同位置。我的意图是使多次出现之间的界限成行。基本上,我的文件可能像下面的
CREATE OR REPLACE TRIGGER "ckjsdnvjn" (ID number, Type varchar2)
BEFORE UPDATE OR INSERT ON TRIGGER_NAME
FOR EACH ROW
BEGIN
IF INSERTING THEN
:NEW.CREATED_D := SYSTIMESTAMP;
ELSE
:NEW.CREATED_D := :OLD.CREATED_D;
END IF;
:NEW.MODIFIED_D := SYSTIMESTAMP;
END;
/
CREATE TABLE kjjknvfskjn
(
ID NUMBER(19,0) NOT NULL,
GRADE VARCHAR2( 4 ) NOT NULL,
MODIFIED_D TIMESTAMP,
CONSTRAINT jnflkvndflkn PRIMARY KEY( ID )
);
CREATE SEQUENCE kcnvlfnvlfnlk;
CREATE OR REPLACE TRIGGER ME(ticket varchar2, note varchar2) AS
BEGIN
INSERT INTO jknsfjknv(
cnkj,
kknvlfn
)
VALUES (
SYS_CONTEXT('lknvl','kvnldfkn'),
'(kljkcsn: ' || lkdnv || ') ' || lknv
);
END ME;
/
预期输出:
匹配1:
CREATE OR REPLACE TRIGGER "ckjsdnvjn" (ID number, Type varchar2)
BEFORE UPDATE OR INSERT ON TRIGGER_NAME
FOR EACH ROW
BEGIN
IF INSERTING THEN
:NEW.CREATED_D := SYSTIMESTAMP;
ELSE
:NEW.CREATED_D := :OLD.CREATED_D;
END IF;
:NEW.MODIFIED_D := SYSTIMESTAMP;
END;
/
匹配2:
CREATE OR REPLACE TRIGGER ME(ticket varchar2, note varchar2) AS
BEGIN
INSERT INTO jknsfjknv(
cnkj,
kknvlfn
)
VALUES (
SYS_CONTEXT('lknvl','kvnldfkn'),
'(kljkcsn: ' || lkdnv || ') ' || lknv
);
END ME;
/
我的伪代码如下,但是我没有得到第二条匹配行之间的行(CREATE OR REPLACE TRIGGER ME),因为还有附加的括号。有没有更好的方法来获得所需的输出?
with open(local_file, 'r') as f:
textfile_temp = f.read()
lines = textfile_temp.splitlines()
STRING = 'CREATE OR REPLACE TRIGGER'
SEARCH_END_STRING = 'end;'
for line in lines:
if re.search(STRING, line, re.IGNORECASE):
line = line.strip()
line = line.replace('(', '\(')
line = line.replace(')', '\)')
print line
SEARCH_PATTERN = r'(' + line + ')(.*?)(' + SEARCH_END_STRING + ')'
SEARCH_REGEX = re.compile(SEARCH_PATTERN, re.IGNORECASE|re.DOTALL|re.MULTILINE)
match = SEARCH_REGEX.search(textfile_temp)
print match.group()
错误:
CREATE OR REPLACE TRIGGER ME\(ticket varchar2, note varchar2\) AS
AttributeError: 'NoneType' object has no attribute 'group'
答案 0 :(得分:1)
使用re.findall
-> Lookbehind & Lookahead
演示:
import re
for i in re.findall(r"(?<=CREATE OR REPLACE).*?(?=\/)", s, flags=re.MULTILINE|re.DOTALL):
print("CREATE OR REPLACE" + i)
print("---")
输出:
CREATE OR REPLACE TRIGGER "ckjsdnvjn" (ID number, Type varchar2)
BEFORE UPDATE OR INSERT ON TRIGGER_NAME
FOR EACH ROW
BEGIN
IF INSERTING THEN
:NEW.CREATED_D := SYSTIMESTAMP;
ELSE
:NEW.CREATED_D := :OLD.CREATED_D;
END IF;
:NEW.MODIFIED_D := SYSTIMESTAMP;
END;
----
CREATE OR REPLACE TRIGGER ME(ticket varchar2, note varchar2) AS
BEGIN
INSERT INTO jknsfjknv(
cnkj,
kknvlfn
)
VALUES (
SYS_CONTEXT('lknvl','kvnldfkn'),
'(kljkcsn: ' || lkdnv || ') ' || lknv
);
END ME;
----