bash bash中冒号后的正则表达式提取字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12569123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:22:17  来源:igfitidea点击:

regular expression extract string after a colon in bash

regexbash

提问by prolink007

I need to extract the string after the :in an example below:

我需要:在下面的示例中提取字符串:

package:project.abc.def

package:project.abc.def

Where i would get project.abc.defas a result.

project.abc.def结果我会得到什么。

I am attempting this in bash and i believe i have a regular expression that will work :([^:]*)$.

我正在 bash 中尝试这个,我相信我有一个可以工作的正则表达式:([^:]*)$

In my bash script i have package:project.abc.defas a variable called apk. Now how do i assign the same variable the substring found with the regular expression?

在我的 bash 脚本中,我有package:project.abc.def一个名为apk. 现在我如何分配与正则表达式找到的子字符串相同的变量?

Where the result from package:project.abc.defwould be in the apkvariable. And package:project.abc.defis initially in the apkvariable?

凡从结果package:project.abc.def将在apk变量。并且package:project.abc.def最初是在apk变量中?

Thanks!

谢谢!

回答by gvalkov

There is no need for a regex here, just a simple prefix substitution:

这里不需要正则表达式,只需简单的前缀替换:

$ apk="package:project.abc.def"
$ apk=${apk##package:}
project.abc.def

The ## syntax is one of bash's parameters expansions. Instead of #, % can be used to trim the end. See this sectionof the bash man page for the details.

## 语法是 bash 的参数扩展之一。可以使用 % 代替 # 来修剪结尾。有关详细信息,请参阅bash 手册页的这一部分

Some alternatives:

一些替代方案:

$ apk=$(echo $apk | awk -F'package:' '{print }')
$ apk=$(echo $apk | sed 's/^package://')
$ apk=$(echo $apk | cut -d':' -f2)

回答by Alex Merelli

$ string="package:project.abc.def"
$ apk=$(echo $string | sed 's/.*\://')

".*:" matches everything before and including ':' and then its removed from the string.

".*:" 匹配包含 ':' 之前的所有内容,然后将其从字符串中删除。

回答by chepner

Capture groups from regular expressions can be found in the BASH_REMATCHarray.

可以在BASH_REMATCH数组中找到来自正则表达式的捕获组。

[[ $str =~ :([^:]*)$ ]]
# 0 is the substring that matches the entire regex
# n > 1: the nth parenthesized group
apk=${BASH_REMATCH[1]}