简体   繁体   English

如何获取以连字符开头的匹配字符串和使用正则表达式的字符

[英]how to get match string that start with hyphen and character with regex

I have two strings 我有两个琴弦

100-2000

and

100-X200-2012

I try to write regex that match both strings like below by saying that if the second hyphen start with X ignore it 我尝试编写匹配两个字符串的正则表达式,如下所示,如果第二个连字符以X开头,则忽略它

[0-9]+-[a-zA-Z0-9 \-X]+-[0-9]

but it fail to match it, I am not sure how to match it with my criteria ? 但它无法匹配,我不确定如何将其与我的条件匹配?

Since you haven't specified a tool, I'll go with the .NET regex flavor (my personal favorite): 由于您尚未指定工具,因此我将使用.NET regex风格(我个人最喜欢):

\d+(-[ \w-[_X]][ \w-[_]]+)?-\d+

\\d is the same as [0-9] \\d[0-9]相同

In .NET, you can use character class subtraction to remove particular elements from a characters class. 在.NET中,您可以使用字符类减法从字符类中删除特定元素。 In this case, I've included a space and a \\w (which is the same as [0-9a-zA-Z_]) within the character class and then subtracted the underscore and uppercase X. 在这种情况下,我在字符类中包含一个空格和一个\\w (与[0-9a-zA-Z_]相同),然后减去了下划线和大写X。

Another option is to use negative lookahead: 另一种选择是使用否定前瞻:

\d+(-(?!X)[ 0-9a-zA-Z]+)?-\d+

I like this even better, but not all flavors of regex support it. 我更好地喜欢它,但是并非所有的正则表达式都支持它。

你的意思是:

[0-9]+-[^X][a-zA-Z0-9 \-]*-[0-9]+

可能是这样的

(\d*)(-X\d*|)-(\d{4})

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

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