在 bash(版本 3.2.48)脚本中,我得到一个字符串,可能类似于:
'XY'
' Y'
'YY'
等
所以,我有一个字母字符或一个空格(第一个插槽),然后是相关字符(第二个插槽)。我尝试了一些变体(没有 grep、sed、...),例如:
if [[ $string =~ ([[:space]]{1}|[[:alpha:]]{1})M ]]; 然后
和
if [[ $string =~ (\s{1}|.{1})M ]]; 然后
但我的解决方案并不总是正常工作(正确匹配每个组合)。
这应该适合你:
if [[ $string =~ [[:space:][:alpha:]]M ]]; then
if [[ ${string:1:1} == "M" ]]; then
echo Heureka
fi
或者(如果你想用模式来做)
if [[ $string =~ ([[:space:]]|[[:alpha:]])M ]]; then
echo Heureka
fi
或(甚至更简单)
if [[ $string == ?M ]]; then
echo Heureka
fi
不使用正则表达式,简单的模式匹配就足够了:
if [[ $string == [[::upper:]\ ]M ]]; then
echo match
fi
鉴于你的例子,你想要[[:upper:]]而不仅仅是[[:alpha:]]