简体   繁体   中英

Regex positive look behind and look ahead

I have some arbitrary output like such:

ABC1    1.1.1.1    20151118    active
ABC2    2.2.2.2    20151118    inactive
xxx     x.x.x.x    xxxxxxxx    active

I am trying to determine a pattern using regex to extract the second column values for lines that contain ABC and active

This is what I have come out with thus far, but I have gotten stuck...

My issue seems to be the whitespaces in between the first column and second column, however Python does not allow variable width patterns in look behinds.

(?<ABC)(\s+)(\d+).(\d+).(\d+).(\d+)(?=\S+\s+active)

No need to use lookbehind. You can use this regex and grab the captured group #1:

^ABC\S+\s+(\S+)(?=.*\sactive\b)

RegEx Demo

Code:

import re
p = re.compile(ur'^ABC\S+\s+(\S+)(?=.*\sactive\b)', re.MULTILINE)

re.findall(p, input)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM