Regex允许在string-bash中使用空格
我无法获取要验证的带空格的字符串。它在没有空格的情况下工作,但是当我在字符串中包含空格时,它就失败了。我已经在谷歌上疯狂搜索了一下,但没能让它正常工作Regex允许在string-bash中使用空格,regex,bash,Regex,Bash,我无法获取要验证的带空格的字符串。它在没有空格的情况下工作,但是当我在字符串中包含空格时,它就失败了。我已经在谷歌上疯狂搜索了一下,但没能让它正常工作 if [[ $string =~ ^"[A-Za-z ]"$ ]]; then # true else # false fi 我不确定这里缺少什么…使用变量存储正则表达式: re='^[A-Za-z ]+$' 然后将其用作: [[ "string" =~ $re ]] && echo "matched" ||
if [[ $string =~ ^"[A-Za-z ]"$ ]]; then
# true
else
# false
fi
我不确定这里缺少什么…使用变量存储正则表达式:
re='^[A-Za-z ]+$'
然后将其用作:
[[ "string" =~ $re ]] && echo "matched" || echo "nope"
matched
[[ "string with spaces" =~ $re ]] && echo "matched" || echo "nope"
matched
如果需要内联正则表达式,请使用:
[[ "string with spaces" =~ ^[A-Za-z\ ]+$ ]] && echo "matched" || echo "nope"
matched
或者使用[[:blank:]
属性:
[[ "string with spaces" =~ ^[A-Za-z[:blank:]]+$ ]] && echo "matched" || echo "nope"
matched
我应该使用下面的正则表达式,如果它总是空格
if [[ $string =~ ^"[A-Za-z ](\s)"$ ]]; then
# true
else
# false
fi
干杯:)看一看。您需要
“^[A-Za-z]*$”
来匹配可以包含0个或多个字母或空格的字符串。这些引号是错误的,即使不存在,此模式也不允许字符串包含除2以外的任何字符数。