如何匹配具有多种可能性的指定模式 [英] How to match a specified pattern with multiple possibilities

查看:38
本文介绍了如何匹配具有多种可能性的指定模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个请求,用 E.*E 替换模式 A.*D.但是我的字符串有多种组合来满足这种模式,比如 bAcDAccDAccccD.如果我只是用正常的方式替换,就得不到我预期的结果,即bEcEEccEEccccE:

I have a request to replace the pattern A.*D with E.*E. however my string have multiple combinations to meet this pattern, like bAcDAccDAccccD. if I just use the normal way to replace, I can't get my expected result, i.e., bEcEEccEEccccE:

echo 'bAcDAccDAccccD'|sed 's/A\(.*\)D/E\1E/g' --> bEcDAccDAccccE.

如何解决此类问题?

推荐答案

* 是贪婪量词(参见 贪婪与不情愿与占有量词).它会尽量匹配

* is greedy quantifier(See Greedy vs. Reluctant vs. Possessive Quantifiers). It will try to match as much as possible

针对给定情况的简单解决方法是

A simple workaround for given case is

$ echo 'bAcDAccDAccccD' | sed 's/A\([^D]*\)D/E\1E/g'
bEcEEccEEccccE

[^D]* 将只匹配非 D 字符,而 .* 将匹配任何字符,包括 D

[^D]* will match only non D characters, whereas .* will match any character, including D

这篇关于如何匹配具有多种可能性的指定模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆