gpt4 book ai didi

regex - Bash:正则表达式:匹配字符串是否是 rsync 的远程主机

转载 作者:行者123 更新时间:2023-12-02 02:38:24 25 4
gpt4 key购买 nike

我认为下面有一个很好的正则表达式行,它适用于我在 Regexbuddy 中所做的测试,但似乎不适用于 bash。

我需要比我更了解正则表达式的人来帮助我。 ;)

重点是对字符串是否包含 rsync 的远程主机进行基本测试。因此,我们正在测试一些有效的内容,例如 username@host:/或 username@host:~/(我也假设 ./?)...

#!/bin/bash

test="foo@bar:/here/path/"
regex='^([\w-_.]*)@([\w-_.:]*):[~./]'

if [[ "${test}" =~ "${regex}" ]]; then
echo "yes, remote host"
else
echo "no, local"
fi

# filter for remote host by regex
# ^ begin at start of line, ( [ match underscore, word & number chars, dashes, fullstops ] in * repetition ) until first @ and then ( [ match underscore, word & number chars, dashes, fullstops, and colons] in * repetition ) until : and then at least [ ~ or . or / )
# so <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b7c4d8dad2d8d9d2f7dfd8c4c39ac0dfd6c3d2c1d2c59a86858499d4d8da" rel="noreferrer noopener nofollow">[email protected]</a>:/path/ will match
# <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="54273b39313b3a310b3c31263165666714656d667a65626c7a647a65" rel="noreferrer noopener nofollow">[email protected]</a>:~/path/ will match
# blah123.user@2001:db8:85a3:8d3:1319:8a2e:370:7348:./path/ will match
# user@wherever:path/ will not, and /<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5a3b34232e3233343d1a292e3b282e33343d74393537" rel="noreferrer noopener nofollow">[email protected]</a>:with/a/slash will not match
# etc

有什么想法吗?

最佳答案

有几个问题:

  • $regex变量不应在 =~ 之后引用,或启用非正则表达式字符串匹配
  • \w不应使用,请使用 [:alnum:] POSIX 字符类,匹配字母和数字
  • -括号表达式中的字符应该是被正确解析为连字符的第一个或最后一个字符。

我还会使用+ (1 个或多个)量词代替 *在模式中强制 @ 前后至少有一个字符.

你可以使用

test="foo@bar:/here/path/"
regex='^([[:alnum:]_.-]+)@([[:alnum:]_.:-]+):[~./]'
if [[ "$test" =~ $regex ]]; then
echo "yes, remote host"
else
echo "no, local"
fi

参见Bash demo .

关于regex - Bash:正则表达式:匹配字符串是否是 rsync 的远程主机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63988092/

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