如何逃脱previously经常EX pression未知字符串? [英] How to escape a previously unknown string in regular expression?

查看:130
本文介绍了如何逃脱previously经常EX pression未知字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要 egrep的未运行前已知的字符串,我会通过shell变量得到(shell是bash,如果该事项)。问题是,该字符串将包含特殊字符,如括号,空格,点,斜线,等等。

I need to egrep a string that isn't known before runtime and that I'll get via shell variable (shell is bash, if that matters). Problem is, that string will contain special characters like braces, spaces, dots, slashes, and so on.

如果我知道我的字符串能逃脱特殊字符的一次,但我怎么能做到这一点整个字符串?

If I know the string I can escape the special characters one at a time, but how can I do that for the whole string?

通过sed脚本,以preFIX与\\运行字符串中的每个特殊字符可能是一个想法,我还需要RTFM这样的脚本应该如何写。我不知道是否有其他更好的,选项。

Running the string through a sed script to prefix each special character with \ could be an idea, I still need to rtfm how such a script should be written. I don't know if there are other, better, options.

我看过 re_format(7),但它似乎有一个像取整下一个字符串文字没有这样的事......

I did read re_format(7) but it seems there is no such thing like "take the whole next string as literal"...

编辑:避免误报,我还要补充换行符检测到的模式,例如。 egrep的'^ myunknownstring

to avoid false positives, I should also add newline detection to the pattern, eg. egrep '^myunknownstring'

推荐答案

如果您需要将字符串嵌入到一个更大的前pression, SED 是怎样我会做。

If you need to embed the string into a larger expression, sed is how I would do it.

s_esc="$(echo "$s" | sed 's/[^-A-Za-z0-9_]/\\&/g')" # backslash special characters
inv_ent="$(egrep "^item [0-9]+ desc $s_esc loc .+$" inventory_list)"

这篇关于如何逃脱previously经常EX pression未知字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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