正则表达式允许字符串中的空格-bash [英] Regex to allow spaces in string - bash

查看:111
本文介绍了正则表达式允许字符串中的空格-bash的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有带空格的字符串来验证.它可以在没有空格的情况下工作,但是当我在字符串中包含空格时,它将失败.我已经用Google搜索了,但无法正常工作.

I can't get a string with spaces to validate. It works without spaces, but when I include a space in the string it fails. I have googled furiously but can't get it to work.

if [[ $string =~ ^"[A-Za-z ]"$ ]]; then
    # true
else 
    # false
fi

我不确定我在这里缺少什么...

I'm not sure what I'm missing here...

推荐答案

使用变量存储您的正则表达式:

Use a variable to store your regex:

re='^[A-Za-z ]+$'

然后将其用作:

[[ "string" =~ $re ]] && echo "matched" || echo "nope"
matched

[[ "string with spaces" =~ $re ]] && echo "matched" || echo "nope"
matched

如果要使用内联正则表达式,请使用:

If you want inline regex then use:

[[ "string with spaces" =~ ^[A-Za-z\ ]+$ ]] && echo "matched" || echo "nope"
matched

否则使用 [[:: blank:]] 属性:

[[ "string with spaces" =~ ^[A-Za-z[:blank:]]+$ ]] && echo "matched" || echo "nope"
matched

这篇关于正则表达式允许字符串中的空格-bash的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆