问题描述
我正在尝试使用C#中的正则表达式来匹配可能包含以下内容的软件版本号:
I'm trying to use a regular expression in C# to match a software version number that can contain:
- 2位数字
- 1或2位数字(不能以0开头)
- 另一个1或2位数字(不是从0开始)
- 1、2、3、4或5位数字(不能以0开头)
- 在方括号内的最后一个选择字母.
一些例子:
10.1.23.26812
83.33.7.5
10.1.23.26812[d]
83.33.7.5[q]
无效的示例:
10.1.23.26812[
83.33.7.5]
10.1.23.26812[d
83.33.7.5q
我尝试了以下操作:
string rex = @"[0-9][0-9][.][1-9]([0-9])?[.][1-9]([0-9])?[.][1-9]([0-9])?([0-9])?([0-9])?([0-9])?([[][a-zA-Z][]])?";
(注意:如果我尝试不使用"@",而只是通过执行"\ ["转义方括号,则会出现错误消息,提示无法识别的转义序列")
(note: if I try without the "@" and just escape the square brackets by doing "\[" I get an error saying "Unrecognised escape sequence")
我可以说版本号可以正确验证,但是它接受之后出现的所有内容(例如:"10.1.23.26812thisShouldBeWrong"被正确匹配).
I can get to the point where the version number is validating correctly, but it accepts anything that comes after (for example: "10.1.23.26812thisShouldBeWrong" is being matched as correct).
所以我的问题是:是否可以使用正则表达式匹配/检查字符串中的方括号,或者我需要将其转换为其他字符(例如:将[a]更改为 a 并匹配* s)?
So my question is: is there a way of using a regular expression to match / check for square brackets in a string or would I need to convert it to a different character (eg: change [a] to a and match for *s instead)?
推荐答案
之所以会发生这种情况,是因为正则表达式匹配字符串的一部分,而您没有告诉它强制整个字符串匹配.另外,您可以简化很多正则表达式(例如,不需要所有捕获组:
This happens because the regex matches part of the string, and you haven't told it to force the entire string to match. Also, you can simplify your regex a lot (for example, you don't need all those capturing groups:
string rex = @"^[0-9]{2}\.[1-9][0-9]?\.[1-9][0-9]?\.[1-9][0-9]{0,4}(?:\[[a-zA-Z]\])?$";
^
和$
是与开头和结尾匹配的锚的字符串.
The ^
and $
are anchors that match the start and end of the string.
您提到的错误消息与以下事实有关:如果不使用逐字字符串,则也需要转义反斜杠.因此,可以在正则表达式中将文字左括号匹配为"[[]"
或"\\["
或@"\["
.后一种形式是首选.
The error message you mentioned has to do with the fact that you need to escape the backslash, too, if you don't use a verbatim string. So a literal opening bracket can be matched in a regex as "[[]"
or "\\["
or @"\["
. The latter form is preferred.
这篇关于C#正则表达式匹配方括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!