Example of "Negative lookahead and lookbehind"

Qustion: Display a large number (like 8927369280) in printed text, it’s often helpful to insert commas between each grouping of three numbers. The rule here is that we want to insert a comma at locations having digits on the right in exact sets of three, and at least one digit on the left. Answer: We can fulfill the second requirement using lookbehind. The simple subexpression (?<=/d) will match locations that have at least one digit to their left. For the second requirement we need to match sets of three numbers up to the end of the string. The simple expression (/d/d/d)+$ accomplishes this task, and if we wrap it in a lookahead construct it will match at locations that are an even set of triple digits from the end of the string. So the completed regular expression
#!/usr/bin/env python
import re

num =  8927369280
print re.sub(r'(?<=/d)(?=(/d/d/d)+$)',',', str(num))
Notes: Take care of the regex part: r'(?<=/d)(?=(/d/d/d)+$)'
### Lookahead 的概念 Lookahead 是正则表达式中的一个重要特性,用于指定某些条件而不实际消耗字符匹配。它允许开发者定义一个模式,在该模式下仅当某个子表达式的匹配成功时才继续后续的匹配过程。 #### 正向肯定 lookahead 正向肯定 lookahead 表达式的形式为 `(?=...)`,表示当前位置之后的内容必须满足括号内的模式才能通过验证[^1]。例如: ```regex \b\d+(?= dollars)\b ``` 上述例子会匹配任何以空格分隔的数字序列,前提是这些数字后面紧跟着字符串 `" dollars"`。注意的是,`" dollars"` 并不会被计入最终的结果中。 #### 反向否定 lookahead 反向否定 lookahead 使用 `(?!...)` 来实现相反的效果——即如果当前位置后的文本不符合给定的模式,则此部分可以匹配成功[^2]。比如下面这个例子用来查找不是由字母组成的单词边界词元: ```regex \w+\b(?!abc) ``` 这里的意思是从左至右扫描每一个可能成为独立单元(word boundary)的地方;只要那个地方不紧接着出现 abc 就算作符合条件的一个整体 word unit。 #### 实际应用案例分析 考虑这样一个需求场景:我们需要提取日期格式但排除掉那些带有特定前缀或者后缀的情况。假设我们的目标数据集中存在多种不同样式的日期记录形式如 dd.mm.yy 和 yyyy-mm-dd ,但是我们希望忽略所有形似 'invalid-date-' 开头或者是 '-not-valid' 结束的部分 。那么我们可以构建如下所示复杂一点却非常实用有效的 regex : ```regex (?<!invalid\-date\-)(\d{2}\.\d{2}|\d{4})-(?!\d*not\-valid$) ``` 在这个复杂的正则里包含了两个方向上的 lookaround 构造来分别处理前置与后置约束条件[^3]。 #### 替换操作中的使用 除了单纯的匹配之外,在涉及到替换的时候也可以巧妙运用lookaheads达到更加精准控制的目的。例如将标准美国电话号码转换成国际拨打版本时可以通过简单的调整完成任务: ```python import re pattern = r"(?<=[\(]?(\d{3}))[-.) ]*(\d{3})[-.]?(\d{4})" text="Call me at (800) 555-1212." result=re.sub(pattern,"+1 (\g<1>) \g<2>-\g<3>", text) print(result) ``` 上面这段脚本利用了Python内置库re模块的功能实现了从原始美式写法到国际化展示样式之间的无缝过渡变换效果[^4]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值