gpt4 book ai didi

python - 如何根据 bash 脚本中的正则表达式拆分字符串

转载 作者:太空狗 更新时间:2023-10-30 02:39:14 25 4
gpt4 key购买 nike

我有这样一个字符串:

msg='123abc456def'

现在我需要拆分 msg 并得到如下结果:

['123', 'abc', '456', 'def']

在 python 中,我可以这样做:

pattern = re.compile(r'(\d+)')
res = pattern.split(msg)[1:]

如何在 bash 脚本中得到相同的结果?
我试过这样但它不起作用:

IFS='[0-9]'    # how to define IFS with regex?
echo ${msg[@]}

最佳答案

使用 grep 获取子字符串,并使用命令替换将输出放入数组中:

$ msg='123abc456def'

$ out=( $(grep -Eo '[[:digit:]]+|[^[:digit:]]+' <<<"$msg") )

$ echo "${out[0]}"
123

$ echo "${out[1]}"
abc

$ echo "${out[@]}"
123 abc 456 def
  • 正则表达式 (ERE) 模式 [[:digit:]]+|[^[:digit:]]+ 匹配一个或多个数字 ([[:digit:]] +) 或 (|) 一个或多个非数字 ([^[:digit:]]+.

关于python - 如何根据 bash 脚本中的正则表达式拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45025516/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com