简体   繁体   中英

Bash match string with regex

I am using bash 4.1.10(4)-release and I trying to use a regex to match against two capital letters [AZ]{2} and then anything. So for example BXCustomerAddress , CAmaterial would be acceptable, but WarehouseMessage would not. I have the following script for testing purposes:

#!/bin/bash

if [[ "Ce" =~ [A-Z]{2} ]]; then
    echo "match"
fi

My questions are:

  1. When I run this script, why does it return that I have a match?
  2. Does anyone know how I could achieve my desired results?

Looks like you have shopt nocaseglob turned on. Turn it off using:

shopt -u nocaseglob

Now [[ "Ce" =~ [AZ]{2} ]] should not match and will return false.

Check the value of the shell option nocasematch :

$ shopt nocasematch
nocasematch     off

shopt nocasematch is probably set to on . Turn it off with

shopt -u nocasematch

From the Bash Reference Manual :

nocasematch

If set, Bash matches patterns in a case-insensitive fashion when performing matching while executing case or [[ conditional commands.

After trying out many different combinations, this is what gave me the expected behavior:

#!/bin/bash
# [A-Z][A-Z] will not work
# [:upper:][:upper:] will not work
# [[A-Z]][[A-Z]] will not work
# [[:upper:]][[:upper:]] does work

echo "test one"
if [[ "CA" =~ ^([[:upper:]][[:upper:]])+ ]]; then
    echo "match"
fi

echo "test two"
if [[ "Ce" =~ ^([[:upper:]][[:upper:]])+ ]]; then
    echo "match"
fi

I get the expected results of:

test one
match
test two

Thanks for everyone's help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM