Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

Python Regex to capture from txt file

I want to write a regex that will match a string only if the string consists of two capital letters (state abbreviations) and the constraints.

The txt file has the following partial values:

VARS 
WA : 1 2 3 4 5 
ID : 1 2 3 4 5 
OR : 1 2 3 4 5 
NV : 1 2 3 4 5 
CA : 1 2 3 4 5 
ENDVARS 
CONSTRAINTS 
!= WA OR 
!= WA ID 
!= CA OR 
!= MA RI 
!= MA CT 
!= CT RI 
ENDCONSTRAINTS

I got stuck at ([A-Z]+) and the cheat sheet is not helpful. I am trying to get two sets: Set 1: Capture (not including the words VARS and ENDVARS)

 WA : 1 2 3 4 5
 ID : 1 2 3 4 5
 OR : 1 2 3 4 5
 NV : 1 2 3 4 5
 CA : 1 2 3 4 5

Set 2: Capture (not including CONSTRAINTS and ENDCONSTRAINTS)

 != WA OR 
 != WA ID 
 != CA OR 
 != MA RI 
 != MA CT 
 != CT RI

I thought adding {2} will mean capturing only 2 characters, for th first set, but not working.

question from:https://stackoverflow.com/questions/65950306/python-regex-to-capture-from-txt-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Looks like these two work for your input file.

Part 1

Two capitals, a space, a colon, a repetition of spaces and digits

[A-Z]{2} :[ 0-9]+

Matches:

WA : 1 2 3 4 5 
ID : 1 2 3 4 5 
OR : 1 2 3 4 5 
NV : 1 2 3 4 5 
CA : 1 2 3 4 5 

Demo

Part 2

Exclamation mark, equal sign, space, a repetition of spaces and capitals

!= [ A-Z]+

Matches:

!= WA OR 
!= WA ID 
!= CA OR 
!= MA RI 
!= MA CT 
!= CT RI 

Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...