简体   繁体   English

正则表达式在数字上的用法

[英]usage of regular expression on numbers

User gives input like 4.0.9 用户输入4.0.9

I have a list of such numbers in a file like 4.0.8, 4.0.9, 4.0.10 etc. In this case i have to select 4.0.9 out of this three. 我在4.0.8, 4.0.9, 4.0.10等文件中有此类数字的列表。在这种情况下,我必须从这三个中选择4.0.9。

But if the file contains like 4.0.8, 4.0.9+, 4.0.10 then I have to copy both 4.0.9 and 4.0.10 . 但是如果文件包含4.0.8, 4.0.9+, 4.0.10类的文件4.0.8, 4.0.9+, 4.0.10那么我必须同时复制4.0.94.0.10

Also if it has like 4.0.8, 4.0.9, 4.0.10+ then I have to copy only 4.0.9 另外,如果它具有4.0.8, 4.0.9, 4.0.10+那么我只需要复制4.0.9

I tried with regular expression in c# but doesn't suite for all test case. 我尝试在C#中使用正则表达式,但不适合所有测试用例。 Any idea how to implement this logic or any in-build function available? 任何想法如何实现此逻辑或任何可用的内置功能?

If I understand you requirements correctly, you can write it in the following way. 如果我正确理解您的要求,则可以通过以下方式编写它。 Assuming you have some list of versions (unsorted), you can parse it to the helper list. 假设您有一些版本 list (未排序),则可以将其解析为帮助程序列表。 Notice that I'm additionaly sorting versions from the list , to make logic clearer: 请注意,我还要从list对版本进行排序,以使逻辑更清晰:

string list = "4.0.8, 4.0.9+, 4.0.10";
var versions =
list.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
    .Select(s => new
    {
       Version = Version.Parse(s.TrimEnd('+')),
       FutureReleases = s.EndsWith("+")
    })
    .OrderBy(a => a.Version);

Then simply iterate through it when matching some specific input : 然后在匹配某些特定input时只需对其进行迭代:

string input = "4.0.9";
var version = Version.Parse(input);
var output = versions.SkipWhile(a => a.Version < version);
var first = output.FirstOrDefault();
if (first != null && !first.FutureReleases)
{
    output = versions.TakeWhile(a => a.Version == version);
}

Here we are just omitting lower version and take single version (if + was not specified) or all higher additionally (if + was specified). 在这里,我们只是省略较低的版本,而取单个版本(如果未指定+ )或全部取而代之(如果指定了+ )。

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

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