如何防止我称之为“正则表达式注入(inject)”的事情?
我正在使用正则表达式来解析可能看起来像的字符串 - 示例之一 -
Size: 10, qty: 20
编写一个正则表达式来捕获“10”和“20”本身并不难。 但是,“大小”和“数量”是可自定义的 - 用户可以选择其他词。
所以我做的是:
var pattern = String.Format(
@"{0}[ \t]*(?<size>{1}|\d*)[ \t]*:[ \t]*{2}:[ \t]*(?<quantity>[\d]*)",
sizeSign,
univerSizeAbbrev,
qtySign);
但我如何“清理”sizeSign、qtySign(或 univerSizeAbbrev)?
Regex 没有像 SQL 那样的过程参数 (?),所以我如何确保,肯定地确保 sizeSign 和 qtySign 始终被视为文字,无论他们是。
最佳答案
使用Regex.Escape :
Escapes a minimal set of characters (\, *, +, ?, |, {, [, (,), ^, $,., #, and white space) by replacing them with their escape codes. This instructs the regular expression engine to interpret these characters literally rather than as metacharacters.
关于c# - 如何防止 "regex injection"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6607880/