简体   繁体   中英

Python Regular expression look behind for column names

我有一个列名列表['aa_bb', 'aa_cc_bb', 'ff_bb']我想返回有bb但没有aacc列,所以上面的结果应该是ff_bb

You don't really have to use regex. You can do this:

for item in lst:
    if "aa" not in item and "cc" not in item and "bb" in item:
        print(item)

I know you asked about look- behind , but you could use a negative look- ahead assertion at the start of your expression. If the string has any aa or cc then the .*(aa|cc) inside the negative look-ahead will match, so the regex as a whole will fail.

(Putting the equivalent negative look-behind at the end would not work, because look-behind cannot contain variable-width patterns such as .* .)

>>> import re
>>> names = ['aa_bb', 'aa_cc_bb', 'ff_bb']
>>> pattern = '(?!.*(aa|cc)).*bb'
>>> [name for name in names if re.match(pattern, name)]
['ff_bb']

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