正则表达最糟糕的情况 [英] Regular Expression Worst Situation

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

问题描述

您好,我正在使用一个reg exp来解决问题,并且无法让它在C#上工作#



文本吧这个



Hello, I am blasting my head off with one reg exp and can't get it working on C#

the text it this

<span class="css-truncate-target">0.1.1.0</span>





我想获得版本: 0.1.1.0



而且C#是:



I want to get the Version: 0.1.1.0

And the C# is:

Match match = Regex.Match(releasesString, @"<span class=""css - truncate - target"">(?:[0-9].[0-9].[0-9].[0-9])<\/span>",
            RegexOptions.IgnoreCase);

            if (match.Success)
            {
                Console.WriteLine(match.Groups[1].Value);
            }





成功总是假的



And the Success is always false

推荐答案

试试这个:

Try this:
(?<=\<span.*\>)\d\.\d\.\d.\d(?=\</span\>)



关键在于:


The keys lie in:

(?<=exp) // zero-width positive lookahead assertion






and

(?=exp) // zero-width positive lookbehind assertion



谷歌并了解更多关于它们的信息。


Google and find out more about them.


这里有太多问题,即使问题非常简单。首先,'。'是一种特殊的正则表达式表示法。所以,逃避它:'\。'。

将每个'[0-9]'术语放在圆括号中,它将帮助你获得匹配和稍后将每个匹配解析为整数。最后,你真的想在每个版本组件中只有一个数字吗?我对此表示怀疑。添加多重性:'+'(表示1或更多)。哦,我差点忘了:在开头加^,最后加
You have too many problems here, even though the problem is extremely simple. First of all, '.' is a special Regular Expression notation. So, escape it: '\.'.
Take each '[0-9]' term in round brackets, it will help you to get set of matches and later parse each of the matches into integer. And finally, do you really want to have only one digit in each version component? I doubt it. Add multiplicity: '+' (which means 1 or more). Oh, and I almost forgot: add ^ at the beginning and




我希望在我描述你所有的错误后,你可以轻松解决问题。



参见:

https://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex%28v=vs.110%29 .aspx [ ^ ],

https://msdn.microsoft.com/en-us/library/e7sf90t3(v = vs.110).aspx [ ^ ],

https://msdn.mi crosoft.com/en-us/library/system.text.regularexpressions.matchcollection%28v=vs.110%29.aspx [ ^ ]。



请注意,我引用了方法匹配,而不是匹配。这是你真正想要的,因为你需要分别匹配版本的每个部分并分别解析所有匹配。



但我会更简单地解决问题:

at the end.
I hope after I described all your mistakes, you can easily solve the problem.

See also:
https://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex%28v=vs.110%29.aspx[^],
https://msdn.microsoft.com/en-us/library/e7sf90t3(v=vs.110).aspx[^],
https://msdn.microsoft.com/en-us/library/system.text.regularexpressions.matchcollection%28v=vs.110%29.aspx[^].

Note that I referenced the method Matches, not Match. This is what you really want, because you need to match each part of the version separately and parse all matches separately.

But I would solve the problem much simpler:
string[] versionParts = versionString.Split('.');
//and then use int.TryParse for each element of the array versionParts





-SA


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

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