本文介绍了从字符串中提取版本号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



如果我传递一个字符串(verstring ==vername.1.19.5)它会返回版本,因为我忽略了Currentver [ 0]。如果我想传递verstring ==1.19.5。



我的意思是我将使用版本名称(vername)或仅版本(1.19)获得两种格式的verstring .5)



Hi all,

if i pass a string (verstring == "vername.1.19.5") it will return the version because i am ignoring Currentver[0]. if i want to pass verstring == "1.19.5".

I mean i will get verstring in both formats with version name(vername) or only version(1.19.5)

public VerInfo(string verString)
        {
            string[] currentVer;

            if (versionString.Contains("."))
                currentVer= versionString.Split(".".ToCharArray());
            else
                currentVer= versionString.Split(":".ToCharArray());

            a= Convert.ToByte(currentVer[1]);
            b= Convert.ToByte(currentVer[2]);
            c= Convert.ToByte(currentVer[3]);
        }





我的尝试:



我试过使用字符串长度,这里字符串长度各不相同





if(versionString.Length> 5 )



What I have tried:

I have tried using the string length, here string length vary's


if (versionString.Length > 5)

推荐答案

public static void Main()
{
  string[] verstring = new string[] { "vername.1.19.5", "1.19.5" };

  Regex r = new Regex(@"(?:vername\.?:)?(\d+)\.(\d+)\.(\d+)");
  for (int n = 0; n < 2; ++n)
  {
    System.Console.Write("Input string: '{0}', extracted numbers: ", verstring[n]);
    Match m = r.Match(verstring[n]);
    if (m.Success)
    {
      for (int i = 0; i < 3; ++i)
        System.Console.Write("'{0}' ", m.Groups[i + 1].Captures[0]);
      System.Console.WriteLine();
    }
  }
}





输出:



Output:

Input string: 'vername.1.19.5', extracted numbers: '1' '19' '5'
Input string: '1.19.5', extracted numbers: '1' '19' '5' 


public void VerInfo(string verString)
{
    string[] currentVer;

    if (verString.Contains("."))
        currentVer = verString.Split(".".ToCharArray());
    else
        currentVer = verString.Split(":".ToCharArray());

    int Index = 0;
    if (currentVer[0].ToLower().Equals("vername"))
        Index = 1;
    else Index;

    byte a = Convert.ToByte(currentVer[Index++]);
    byte b = Convert.ToByte(currentVer[Index++]);
    byte c = Convert.ToByte(currentVer[Index]);
}

您可以通过替换为三元运算符来进一步细化IF-ELSE语句。为了清楚起见,我没有这样做。

You can further refine the IF-ELSE statement by replacing with ternary operator. I didn't do that for sake of clarity.


这篇关于从字符串中提取版本号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 16:29