help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] bash variables and regex comparison, [[ ]] builtin


From: Greg Wooledge
Subject: Re: [Help-bash] bash variables and regex comparison, [[ ]] builtin
Date: Fri, 22 Jan 2016 08:53:51 -0500
User-agent: Mutt/1.4.2.3i

On Fri, Jan 22, 2016 at 10:30:28AM +0100, Lunda Jaroslav wrote:
>    Let x='abc.xyz' and y='abc:xyz' so that the following holds true
>    (prints "matches" and "diff"): [[ "${x}" =~ abc".xyz" ]] && echo
>    "matches" [[ "${y}" =~ abc".xyz" ]] || echo "diff" Now, literal
>    l=".xyz" can be extracted and tests still work (note double quotes
>    around l refs): [[ "${x}" =~ abc"${l}" ]] && echo "matches" [[ "${y}"
>    =~ abc"${l}" ]] || echo "diff" And the problem: if we try further
>    r="abc\"${l}\"" or r="abc${l}", the first test never prints "matches":
>    [[ "${x}" =~ ${r} ]] && echo "matches" [[ "${y}" =~ ${r} ]] || echo
>    "diff" What should be the proper form of r to pass both tests?

Ouch, what text editor did that?

You are trying to embed quotes INTO a regular expression, and hoping to
have =~ treat them as anything other than literal characters?  Madness.

If you want the . in a regular expression to be treated as a literal
period instead of a single-character wildcard, you must backslash-escape
it.  That's all there is to it.

If you want the entire pattern in $r to be matched as a literal string,
don't use =~ and DO quote "$r" on the right hand side of =.

If you want PART of the pattern in $r to be treated as a literal string,
and PART of the pattern in $r to be treated as a glob or a regular
expression, then you have to use the stronger of the applicable operators
and you have to escape the parts of $r that are to be treated as literal
string characters instead of glob/RE characters.

Embedding \" inside the pattern is not how you escape metacharacters in
this context.  Embedding \ is.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]