【问题标题】:Bash Script Regex match can't escape double quotesBash Script Regex 匹配无法转义双引号
【发布时间】:2015-04-10 05:00:17
【问题描述】:

我尝试了不同的变体来实现以下目标,但我就是做不到。

#!/bin/bash

sb_command_passed=$*
regexMatch="^find every file matching '(.*)' in this folder and subfolders"
[[ $sb_command_passed =~ $regexMatch ]]
param1=${BASH_REMATCH[1]}
echo $param1

现在将以下内容传递给脚本:

find every file matching "search" in this folder and subfolders

它没有返回 search 作为匹配的参数。如果成功,我想在其中传递一个正则表达式:

find every file matching "\s.+[^&*]" in this folder and subfolders

并得到 \s.+[^&*] 作为回报。你能帮我解决这个问题吗?

【问题讨论】:

  • 你为什么要传递字符串 "find every file matching "\s.+[^&*]" in this folder and subfolders" 而不仅仅是你实际想要的 - "\s.+[^&*]"
  • 去掉单引号即可:regexMatch="^find every file matching (.*) in this folder and subfolders"
  • @Tomalak 好吧,这实际上是问题所在,我需要将整个句子传递给我的脚本。
  • @morgano 是的,我知道它确实匹配并以您的方式返回捕获,但这不是我想要做的。

标签: regex bash shell


【解决方案1】:

看起来你只是把你的引号弄错了。这有效:

$ regexMatch='^find every file matching "(.*)" in this folder and subfolders'
$ sb_command_passed='find every file matching "\s.+[^&*]" in this folder and subfolders'
$ [[ $sb_command_passed =~ $regexMatch ]] && echo "${BASH_REMATCH[1]}"
\s.+[^&*]

单引号围绕整个字符串,双引号围绕您要捕获的部分。

【讨论】:

  • 我不能用双引号做点什么吗?也许转义一个序列?
  • 您的意思是您希望能够在模式中包含双引号?
  • 是的,这正是我的意思。
猜你喜欢
  • 2015-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-30
  • 1970-01-01
  • 1970-01-01
  • 2014-05-02
相关资源
最近更新 更多