简体   繁体   English

简单的C#正则表达式问题

[英]Simple C# regex question

Question : What's the simplest way how to test if given Regex matches whole string ? 问题 :如果给定Regex匹配整个字符串,如何测试的最简单方法是什么?

An example: Eg given Regex re = new Regex("."); 一个例子:例如,给定Regex re = new Regex("."); I want to test if given input string has only one character using this Regex re . 我想测试给定的输入字符串是否只有一个字符使用此正则表达式re How do I do that ? 我怎么做 ?

In other words : I'm looking for method of class Regex that works similar to method matches() in class Matcher in Java ("Attempts to match the entire region against the pattern."). 换句话说 :我正在寻找类Regex方法,它类似于Java类Matcher中的方法matches() (“尝试将整个区域与模式匹配。”)。

Edit: This question is not about getting length of some string . 编辑: 这个问题不是关于获取某些string长度。 The question is how to match whole strings with regular exprestions. 问题是如何将整个字符串与常规表达式匹配。 The example used here is only for demonstration purposes (normally everybody would check the Length property to recognise one character strings). 此处使用的示例仅用于演示目的(通常每个人都会检查Length属性以识别一个字符串)。

If you are allowed to change the regular expression you should surround it by ^( ... )$ . 如果你被允许改变正则表达式,你应该用^( ... )$来包围它。 You can do this at runtime as follows: 您可以在运行时执行此操作,如下所示:

string newRe = new Regex("^(" + re.ToString() + ")$");

The parentheses here are necessary to prevent creating a regular expression like ^a|ab$ which will not do what you want. 这里的括号是必要的,以防止创建像^a|ab$这样的正则表达式,它不会做你想要的。 This regular expression matches any string starting with a or any string ending in ab . 此正则表达式匹配以a开头a任何字符串或以ab结尾的任何字符串。


If you don't want to change the regular expression you can check Match.Value.Length == input.Length . 如果您不想更改正则表达式,可以检查Match.Value.Length == input.Length This is the method that is used in ASP.NET regular expression validators. 这是ASP.NET正则表达式验证器中使用的方法。 See my answer here for a fuller explanation. 在此处查看我的答案以获得更全面的解释。

Note this method can cause some curious issues that you should be aware of. 请注意,此方法可能会导致一些您应该注意的奇怪问题。 The regular expression "a|ab" will match the string 'ab' but the value of the match will only be "a". 正则表达式“a | ab”将匹配字符串'ab',但匹配的值将仅为“a”。 So even though this regular expression could have matched the whole string, it did not. 因此即使这个正则表达式可以匹配整个字符串,它也没有。 There is a warning about this in the documentation. 文档中有关于此的警告。

use an anchored pattern 使用锚定模式

Regex re = new Regex("^.$");

for testing string length i'd check the .Length property though ( str.Length == 1 ) … 测试字符串的长度我会检查.Length属性虽然( str.Length == 1 )...

"b".Length == 1

是一个比...更好的候选人

Regex.IsMatch("b", "^.$")

您添加“字符串开头”和“字符串结束”锚点

^.$

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM