开发者

Regex to find a word, then extract a line containing the first occurence of a different word immediately before the original word?

World's most convuluted title I know, an example should explain it better. I have a large txt file in the below format, though details and amount of lines will change everytime:

Username: john_joe                    Owner:  John Joe
Account:  
CLI:      
Default:  
LGICMD:   
Flags: 
Primary days:
Secondary days: 
No access开发者_开发问答 restrictions
Expiration: 
Pwdlifetime:
Last Login: 
Maxjobs:    
Maxacctjobs:
Maxdetach:  
Prclm:      
Prio:       
Queprio: 
CPU:     
Authorized Privileges: 
  BYPASS
Default Privileges: 
  SYSPRV

This sequence is repeated a couple of thousand times for different users. I need to find every user (ideally the entire first line of the above) that has SYSPRV under "Default Permissions". I know I could write an application to do this, I was just hoping their might be a nice regex I could use.

Cheers


^Username:\s*(\S+)((?!^Username).)*Default Privileges:\s+SYSPRV

with the option to make ^ match start of line, and to make dot match newlines, will isolate those records and capture the username in backreference no. 1. Tell me which language you're using, and I'll provide a code sample.

Explanation:

^Username:\s: match "Username" at the start of the line, a colon and any whitespace.

(\S)+": match any non-whitespace characters and capture them into backreference no. 1. This will be the Username.

((?!Username).)*: Match any character as long as it's not the "U" of "Username". This ensures that we won't accidentally cross over into the next record.

Default Privileges:\s+SYSPRV: match the required text.

So in Python, for example, you would use:

result = re.findall(r"(?sm)^Username:\s*(\S+)((?!^Username).)*Default Privileges:\s+SYSPRV", subject)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜