[英]Regular expression: take string literally with special re-characters
Maybe simple question..也许简单的问题..
String text = "fake 43 60 fake";
String patt = "[43.60]";
Match m = Regex.Match(text, patt)
In this situation, m.Success = true because the dot replace any character (also the space).在这种情况下,m.Success = true 因为点替换了任何字符(也是空格)。 But I must match the string literally in the patt.
但我必须在 patt 中逐字匹配字符串。
Of course, I can use the '\' before the dot in the patt当然,我可以在 patt 中的点之前使用 '\'
String patt = @"[43\.60]";
So the m.Success = false, but there's more special characters in the Regular Expression-world.所以 m.Success = false,但在正则表达式世界中还有更多特殊字符。
My question is, how can I use regular expression that a string will be literally taken as it set.我的问题是,我怎样才能使用正则表达式来将字符串按字面意思设置。 So '43.60' must be match with exactly '43.60'.
所以“43.60”必须与“43.60”完全匹配。 '43?60' must be match with '43?60'....
'43?60' 必须与 '43?60' 匹配......
thanks.谢谢。
To get a regex-safe literal:要获得正则表达式安全的文字:
string escaped = Regex.Escape(input);
For example, to match the literal [43.60]
:例如,要匹配文字
[43.60]
:
string escaped = Regex.Escape(@"[43.60]");
gives the string with content: \[43\.60]
.给出内容为:
\[43\.60]
的字符串。
You can then use this escaped content to create a regex;然后,您可以使用此转义内容创建正则表达式; for example:
例如:
string find = "43?60";
string escaped = Regex.Escape(find);
bool match = Regex.IsMatch("abc 43?60", escaped);
Note that in many cases you will want to combine the escaped string with some other regex fragment to make a complete pattern.请注意,在许多情况下,您会希望将转义字符串与其他一些正则表达式片段组合以形成完整的模式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.