gpt4 book ai didi

regex - 使用 match 在只有 bash 的字符串中查找子字符串

转载 作者:行者123 更新时间:2023-11-29 08:41:24 25 4
gpt4 key购买 nike

虽然我几乎可以肯定这已经被涵盖了,但我似乎找不到任何具体的内容。在我继续学习 bash 的过程中,我不断发现让我感到困惑的地方,为什么事情会这样发生。

搜索和替换或仅匹配字符串中的子字符串很可能是您在编写脚本时要做的第一件事。但是,在 bash 中很难坚持使用一种语言或一组工具,因为您可以通过多种方式解决大多数问题。我正在尽最大努力使 bash 保持尽可能低的水平。我遇到了一个障碍,我需要有人向我解释。

在 bash 中使用 match 进行子字符串搜索会根据我使用的正则表达式给出不同的结果,我不确定为什么。

#!/bin/bash
Stext="Hallo World"
echo `expr "$Stext" : '^\(.[a-z]*\)'` # Hallo
echo `expr "$Stext" : '.*World'` # 11

我认为虽然两者都搜索了一个词,但都没有返回他们找到的内容。为什么?

最佳答案

您可以在 bash 中使用 BASH_REMATCH 变量来获取匹配的字符串:

$ Stext="Hallo World"
$ [[ $Stext =~ ^.[a-z]* ]] && echo $BASH_REMATCH
Hallo
$ [[ $Stext =~ ^(.[a-z]*) ]] && echo ${BASH_REMATCH[1]}
Hallo

Substrings matched by parenthesized subexpressions within the regular expression are saved in the array variable BASH_REMATCH. The element of BASH_REMATCH with index 0 is the portion of the string matching the entire regular expression. The element of BASH_REMATCH with index n is the portion of the string matching the nth parenthesized subexpression.

关于regex - 使用 match 在只有 bash 的字符串中查找子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9597751/

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