如何使用正则表达式和 shell 从字符串中提取值?

问题描述:

我在 shell 中,我有这个字符串:12 BBQ ,45 rofl, 89 lol

I am in shell and I have this string: 12 BBQ ,45 rofl, 89 lol

使用正则表达式:\d+ (?=rofl),我想要 45 作为结果.

Using the regexp: \d+ (?=rofl), I want 45 as a result.

使用正则表达式从字符串中提取数据是否正确?我所做的最好的事情是在一些在线正则表达式编辑器中突出显示价值.大多数情况下,它会从我的字符串中删除该值.

Is it correct to use regex to extract data from a string? The best I have done is to highlight the value in some of the online regex editor. Most of the time it remove the value from my string.

我正在调查 expr,但我得到的只是语法错误.

I am investigating expr, but all I get is syntax errors.

如何在 shell 脚本中提取 45?

How can I manage to extract 45 in a shell script?

你可以用 GNU grep 的 perl 模式做到这一点:

You can do this with GNU grep's perl mode:

echo "12 BBQ ,45 rofl, 89 lol" | grep -P '\d+ (?=rofl)' -o
echo "12 BBQ ,45 rofl, 89 lol" | grep --perl-regexp '\d+ (?=rofl)' --only-matching

-P--perl-regexp 表示 Perl 风格的正则表达式.-o--only-matching 表示只输出匹配的文本.

-P and --perl-regexp mean Perl-style regular expression. -o and --only-matching mean to output only the matching text.