正则表达式使用egrep获取分隔内容

发布于 2024-12-17 14:27:23 字数 256 浏览 1 评论 0原文

我想使用正则表达式获取函数调用的参数(不带括号)。

我在 cygwin 的 bash 脚本中使用 egrep

这是我到目前为止得到的(带括号):

$ echo "require(catch.me)" | egrep -o '\((.*?)\)'
(catch.me)

这里正确的正则表达式是什么?

I would like to get the parameter (without parantheses) of a function call with a regular expression.

I am using egrep in a bash script with cygwin.

This is what I got so far (with parantheses):

$ echo "require(catch.me)" | egrep -o '\((.*?)\)'
(catch.me)

What would be the right regex here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

余罪 2024-12-24 14:27:23

http://www.greenend.org.uk/rjk/2002/06 /regexp.html

您在寻找什么 - 是向后查找和向前查找正则表达式。

Egrep 无法做到这一点。具有 Perl 支持的 grep 可以做到这一点。

来自 man grep

 -P, --perl-regexp
          Interpret PATTERN as a Perl regular expression.  This is highly experimental and grep -P may warn of unimplemented features.

所以

gt; echo "require(catch.me)" | grep -o -P '(?<=\().*?(?=\))'
catch.me

http://www.greenend.org.uk/rjk/2002/06/regexp.html

What are you looking for - is a lookbehind and lookahead regular expressions.

Egrep cannot do that. grep with perl support can do that.

from man grep:

 -P, --perl-regexp
          Interpret PATTERN as a Perl regular expression.  This is highly experimental and grep -P may warn of unimplemented features.

So

gt; echo "require(catch.me)" | grep -o -P '(?<=\().*?(?=\))'
catch.me
何处潇湘 2024-12-24 14:27:23

如果您可以使用 sed,那么以下内容将起作用 -

echo "require(catch.me)" | sed 's/.*[^(](\(.*\))/\1/'

您可以将现有的正则表达式修改为此

echo "require(catch.me)" | egrep -o 'c.*e'

尽管egrep提供了此功能(来自手册页),

-o, --only-matching
              Show only the part of a matching line that matches PATTERN.

但这并不是真正正确的实用程序。 SED 和 AWK 是这方面的大师。使用 SED 或 AWK 您将拥有更多控制权。 :)

If you can use sed then the following would work -

echo "require(catch.me)" | sed 's/.*[^(](\(.*\))/\1/'

You can modify your existing regex to this

echo "require(catch.me)" | egrep -o 'c.*e'

Even though egrep offers this (from the man page)

-o, --only-matching
              Show only the part of a matching line that matches PATTERN.

It isn't really the correct utility. SED and AWK are masters at this. You will have much more control using either SED or AWK. :)

从手册中:

   grep, egrep, fgrep - print lines matching a pattern

基本上,grep 用于打印完整的行,因此您无需执行任何其他操作。

您应该做的是使用另一个工具(也许是 perl)来进行此类操作。

From the manual :

   grep, egrep, fgrep - print lines matching a pattern

Basically, grep is used to print the complete line, so you won't do anything more.

What you should do is using another tool, maybe perl, for such operations.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文