正则表达式+最大长度问题 [英] RegEx + maximum length issue

查看:108
本文介绍了正则表达式+最大长度问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伙计们,

.NET 4.0中的正则表达式让我有些迷茫.无法理解RegEx为什么忽略模式中的最大长度.参见下面的代码...

Guys,

I''ve got a little lost with regular expressions in .NET 4.0. Can''t understand why RegEx ignores maximum length in the pattern. See the code below...

using System;
using System.Text.RegularExpressions;

namespace RegExTests
{
	class Program
	{
		static void Main()
		{
			bool result1 = Regex.IsMatch("ABCDEF", @"[A-Z]{2}");
			bool result2 = Regex.IsMatch("ABCDEF", @"[A-Z]{2,2}");

			bool result3 = Regex.IsMatch("AB", @"[A-Z]{,2}");
			bool result4 = Regex.IsMatch("AB", @"[A-Z]{2,2}");
		}
	}
}


我需要实现的是解析一个国家代码,该国家代码恰好是两个大写字母.在所示示例中,RegEx理解最小值,但完全忽略了最大值.结果,输出如下:


What I need to achieve, is to parse a country code that''s expected to be precisely two capital letters. In the example shown RegEx understands the minimum, but completely ignores the maximum. As a result, the output is as follows:

result1 = true;
result2 = true;
result3 = false;
result4 = true;



我不太确定result3的预期结果,但是为什么result2确实是正确的?我不明白...

请指出我在那里做错了.

谢谢!



I''m not quite sure what to expect for result3, but why on earth result2 is true? I don''t get it...

Please point out what I''m doing wrong there.

Thank you!

推荐答案

我想应该是这样的:

I guess it should be like this:

bool result1 = Regex.IsMatch("ABCDEF", @"^[A-Z]{2}


"); bool result2 = Regex.IsMatch(" span>, @"
"); bool result2 = Regex.IsMatch("ABCDEF", @"^[A-Z]{2,2}


" ); bool result3 = Regex.IsMatch(" @"
"); bool result3 = Regex.IsMatch("AB", @"^[A-Z]{,2}


这篇关于正则表达式+最大长度问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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