如何从一行文本中提取int?

时间:2016-12-19 07:02:00

标签: c# string

我在一些数据解析中遇到了麻烦,因为我正在解析的标题行有些复杂。它有年份,标题和版本,但并不总是按顺序排列。年份和版本可以转换为整数但其余的不可以。如果我不知道每次在线上的位置,我怎么能将年份从要解析的其余部分拆分成一个int?

示例数据集:

2016年超级特殊常规赛,01年第15次折腾

数学问题嘉豪2013年第02轮导演问题

FooBar惊人的游戏部分1 0f 2轮03问题2015

我知道我不能只测试整行,看是否有一个数字,因为有多个数字。由于不提前知道日期,我也不能做像IndexOf这样的事情。

5 个答案:

答案 0 :(得分:5)

  

要从字符串中获取所有数字,请使用regex.Matches()方法获取   来自正则表达式的所有匹配

     /* \d+ Is used to find integers */
     Regex regex = new Regex(@"\d+"); 

     // Loop thrue all matches 
     foreach (Match match in regex.Matches("2016 Super special regular season, 01 fifteenth tossup"))
     {
         Console.WriteLine(match.Value); /* Test output */
         int i = Convert.ToInt32(match.Value); /* Convert To Int and do something with it */
     }

      ============ output ===========
      2016
      01


     /* Use this \d{4} to return the 4 character from current match from \d*/
     /* (Example) => 12564568 => (output) : 1256 and 4568 */
     /* (Notice!!) If you use \d{4} and there are only 2 numbers found by \d
        It has no result. */
  

或者在一行中从第一个出现的数字中获取结果值:

    string resultString = Regex.Match(subjectString /*string to test */, @"\d+").Value;

答案 1 :(得分:3)

使用正则表达式:

    string pattern_Year = @"\(\d{4}\)";
    string pattern_Edition = @"\(\d{2}\)";
    string search = "2016 Super special regular season, 01 fifteenth tossup";
    var year = Regex.Matches(search, pattern_Year );
    var edition = Regex.Matches(search, pattern_Edition );
    if(year.Count > 0)
      Console.WriteLine(year[0].Value);
    if(edition.Count > 0)
      Console.WriteLine(edition [0].Value);

答案 2 :(得分:1)

var line = "FooBar the amazing game part 1 0f 2 round 03 problems 2015";

var numbers = line.Split(' ').Where(word => word.All(char.IsDigit)).Select(int.Parse).ToList();

现在你有了第1,第2,第3,2015年。

您如何知道今年的情况取决于您。也许检查哪一次是在1900年到2017年之间?

答案 3 :(得分:1)

这样的事情:

$files = $_FILES['formFieldName'];
$sizes = $files['size'];
arsort($sizes); //sort in descending order but will preserve the keys
$files2 = array();
$i = 0;
foreach ($sizes as $key => $size) {
    $files2['name'][$i] = $files['name'][$key];
    $files2['type'][$i] = $files['type'][$key];
    $files2['tmp_name'][$i] = $files['tmp_name'][$key];
    $files2['error'][$i] = $files['error'][$key];
    $files2['size'][$i] = $size;
    $i++;
}

答案 4 :(得分:1)

试试这个,应该有效

    string strValue = "abc123def456";
    char[] charArr = strValue.ToCharrArray();
    List<int> intList = new List<int>();
   for(int i =0; i < charArr.Length; i++)
      {
         string tmpInt ="";
         if(char.IsDigit(charArr[i]))
           {
            tmpInt += charArr[i];
             while((i < charArr.Lenght -1 ) && char.IsDigit([i + 1)
                 {
                   tmpInt += charArr[i+1];
                   i++;
                 }
           }
          if(tmpInt != "")
          intList.Add(int.Parse(tmpInt));
      }

这个脚本的优点是,字符串中的数字位置并不依赖于拆分或任何模式。