PCRE 正则表达式到 SED [英] PCRE Regex to SED

查看:63
本文介绍了PCRE 正则表达式到 SED的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试采用 PCRE 正则表达式并在 SED 中使用它,但我遇到了一些问题.请注意,这个问题代表了一个更大的问题(如何将 PCRE regex 转换为与 SED 一起使用),因此问题不仅仅是关于下面的示例,而是关于如何在 SED regex 中整体使用 PCRE regex.

I am trying to take PCRE regex and use it in SED, but I'm running into some issues. Please note that this question is representative of a bigger issue (how to convert PCRE regex to work with SED) so the question is not simply about the example below, but about how to use PCRE regex in SED regex as a whole.

此示例从一行中提取电子邮件地址,并将其替换为[emailaddr]".

This example is extracting an email address from a line, and replacing it with "[emailaddr]".

echo "My email is abc@example.com" | sed -e 's/[a-zA-Z0-9]+[@][a-zA-Z0-9]+[\.][A-Za-z]{2,4}/[emailaddr]/g'

我尝试了以下替换正则表达式:

I've tried the following replace regex:

([a-zA-Z0-9]+[@][a-zA-Z0-9]+[\.][A-Za-z]{2,4})
[a-zA-Z0-9]+[@][a-zA-Z0-9]+[\.][A-Za-z]{2,4}
([a-zA-Z0-9]+[@][a-zA-Z0-9]+[.][A-Za-z]{2,4})
[a-zA-Z0-9]+[@][a-zA-Z0-9]+[.][A-Za-z]{2,4}

我已经尝试将 sed 的分隔符从 s/find/replace/g 更改为 s|find|replace|g,如下所述 此处(堆栈溢出:pcre regex 到 sed regex).

I've tried changing the delimited of sed from s/find/replace/g to s|find|replace|g as outlined here (stack overflow: pcre regex to sed regex).

我仍然无法弄清楚如何在 SED 中使用 PCRE 正则表达式,或者如何将 PCRE 正则表达式转换为 SED.任何帮助都会很棒.

I am still not able to figure out how to use PCRE regex in SED, or how to convert PCRE regex to SED. Any help would be great.

推荐答案

使用 -r 标志启用 扩展正则表达式.( -E 而不是 -rOS X )

Use the -r flag enabling the use of extended regular expressions. ( -E instead of -r on OS X )

echo "My email is abc@example.com" | sed -r 's/[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[A-Za-z]{2,4}/[emailaddr]/g'

Ideone 演示

这篇关于PCRE 正则表达式到 SED的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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