2017-01-26 2 views
3

정규식을 사용하여 혼합 된 알파 문장을 나타내는 문자열에서 일련의 숫자를 추출하고 싶습니다.혼합 된 숫자 문자열에서 숫자 만 추출합니다.

예 :

"Please buy 40 kg of apples for 1350$ each"     --> "40|1350" 
"Please call 8 0 0 4 3 2 1 2 4 3 from 17:00 till 22:00"  --> "8004321243|1700|2200" 
"I would like to bid 50 euro on 20 black and pair of spades" --> "50|20" 

따라서 숫자 만 추출하고, 그 사이에 어떤 단어 | 세퍼레이터로 절단한다. 자릿수가 단어가 아닌 문자로 구분되는 경우 두 번째 예와 동일한 숫자로 간주됩니다.

답변

1

먼저 자리를 더한 단어가 아닌 문자 다음에 숫자를 검색하려고 정규식을 살균 할 수 나중에 일치 :

var str = "Please call 8 0 0 4 3 2 1 2 4 3 from 17:00 till 22:00"; 

var regex1 = new Regex(@"([\d]+[\d\W]*)"); 
var regex2 = new Regex(@"([\W]+)");  

foreach (var match in regex1.Matches(str).Cast<Match>()) 
{ 
    var val = match.Groups[1].Value;  

    foreach (var nonWordMatch in regex2.Matches(val).Cast<Match>()) 
    { 
     val = val.Replace(nonWordMatch.Value, ""); 
    } 

    var number = Int64.Parse(val); 
    Console.WriteLine(">> num " + number); 
} 
+1

작동! 감사. – user1395570

0
StringBuilder number = new StringBuilder(); 
List<string> test = new List<string>(); 

foreach (char c in s) 
    { 
     if (Char.IsDigit(c)) { 
      number.append(c); 
     } 
     else if (c == ' ' || c == ':') { 
      //donnothing 
     } 
     else { 
      if (number.Length > 0) { 
      test.add(number.ToString()); 
      number.Clear(); 
      } 
     } 
    } 
0

Regex.Replace(s, @"\W+", "") 모든 단어가 아닌 문자를 제거하고 모든 자리 덩어리를 추출 간단한 \d+ 패턴 :

var res = Regex.Matches(Regex.Replace(s, @"\W+", ""), @"\d+") 
     .Cast<Match>() 
     .Select(m=>m.Value) 
     .ToList(); 

C# demo를 참조하십시오.

관련 문제