【发布时间】:2013-09-08 14:00:04
【问题描述】:
我正在尝试检查长度为 1 的字符串是否只有以下字符:[RGWBO]。
我正在尝试以下方法,但它不起作用,我错过了什么?
if [[ !(${line[4]} =~ [RGWBO]) ]];
【问题讨论】:
-
$line中的第五个元素? -
您能否提供一个数据集样本来澄清您的问题?
标签: bash
我正在尝试检查长度为 1 的字符串是否只有以下字符:[RGWBO]。
我正在尝试以下方法,但它不起作用,我错过了什么?
if [[ !(${line[4]} =~ [RGWBO]) ]];
【问题讨论】:
$line 中的第五个元素?
标签: bash
这就是你想要的:
if [[ ${line[4]} =~ ^[RGWBO]+$ ]];
这意味着从开头到结尾的字符串必须包含一次或多次 [RGWBO] 字符。
如果你想否定表达式,只需在[[ ]]前面使用!:
if ! [[ ${line[4]} =~ ^[RGWBO]+$ ]];
或者
if [[ ! ${line[4]} =~ ^[RGWBO]+$ ]];
【讨论】:
这个可以与任何可用的 Bash 版本一起使用:
[[ -n ${LINE[0]} && ${LINE[0]} != *[^RGWB0]* ]]
尽管我更喜欢扩展 glob 的简单性:
shopt -s extglob
[[ ${LINE[0]} == +([RGWBO]) ]]
【讨论】:
使用expr(表达式求值器)来做substring matching。
#!/bin/bash
pattern='[R|G|W|B|O]'
string=line[4]
res=`expr match "$string" $pattern`
if [ "${res}" -eq "1" ]; then
echo 'match'
else
echo 'doesnt match'
fi
【讨论】:
${#myString}测试字符串长度,如果等于1,继续步骤2;re='[RGWBO]';
while read -r line; do
if (( ${#line} == 1 )) && [[ $line == $re ]]; then
echo "yes: $line"
else
echo "no: $line"
fi
done < test.txt
您可能想查看以下链接:
${#myString};${myString:0:8};test.txt 文件包含此内容
RGWBO
RGWB
RGW
RG
R
G
W
B
O
V
【讨论】: