2016-09-29 39 views
5

我有對象的樣本串'((1/1000)*2375.50)'.NET正則表達式獲取整數ONLY,排除整個DECIMAL

我想要得到的1和1000這是一個INT

我想這個表達式表達:

  • -?\d+(\.\d+)? =>此匹配1, 1000, and 2375.50
  • -?\d+(?!(\.|\d+)) =>此匹配1, 1000, and 50
  • -?\d+(?!\.\d+&(?![.]+[0-9]))? =>1, 1000, 2375, and 50

什麼表情,我必須使用相匹配(1 and 1000)?

+0

所有輸入字符串的格式爲'((x/y)* z)'? – Chrono

+1

@Chrono:不,這只是一個示例字符串。任何字符串都會做 –

回答

4

所以基本上你需要匹配不受小數點或其它數字之前或之後的數字序列?爲什麼不試試這個?

[TestCase("'((1/1000)*2375.50)'", new string[] { "1", "1000" })] 
[TestCase("1", new string[] { "1" })] 
[TestCase("1 2", new string[] { "1", "2" })] 
[TestCase("123 345", new string[] { "123", "345" })] 
[TestCase("123 3.5 345", new string[] { "123", "345" })] 
[TestCase("123 3. 345", new string[] { "123", "345" })] 
[TestCase("123 .5 345", new string[] { "123", "345" })] 
[TestCase(".5-1", new string[] { "-1" })] 
[TestCase("0.5-1", new string[] { "-1" })] 
[TestCase("3.-1", new string[] { "-1" })] 
public void Regex(string input, string[] expected) 
{ 
    Regex regex = new Regex(@"(?:(?<![.\d])|-)\d+(?![.\d])"); 
    Assert.That(regex.Matches(input) 
      .Cast<Match>() 
      .Select(m => m.ToString()) 
      .ToArray(), 
     Is.EqualTo(expected)); 
} 

似乎工作。

+0

你的模式工作就像一個魅力,工作在任何STRING –

+0

@Bienvenido,首先,這是沒有理由的SCREAM。另一件事,正如Kobi指出的那樣,我完全忘記了減號。請參閱我的編輯。 –

1

Try this:

string pattern = @"\(\(([\d]+)\/([\d]+)\)\*"; 
    string input = @"'((1/1000)*2375.50)'"; 


    foreach (Match match in Regex.Matches(input, pattern)) 
    { 
    Console.WriteLine("{0}", match.Groups[1].Value); 
    Console.WriteLine("{0}", match.Groups[2].Value); 

    }   
+0

Tahnks的答案。我試過了,但模式匹配'((1/1000)*'我只想要1和1000 –

+0

你現在可以試試 –

3

您可以使用:

(?<!\.)-?\b\d+\b(?!\.) 

Working example

  • (?<!\.) - 在號碼前無期。
  • -? - 可選的減號
  • \b\d+\b - 數字。用單詞邊界包裹,因此不可能與另一個數字相匹配(例如,與12345.6中的1234不匹配)。這與2pi中的2不匹配。
  • (?!\.) - 號碼後沒有句號。
+0

比我好,因爲儘管有減號和整數可能是標識符的一部分 –

+0

@ SergeyTachenov - 謝謝!減號是問題的一部分(所有模式都以' - ?'開頭)。'2pi'可能是我的模式中的一個錯誤,我們可能想要匹配這些整數 – Kobi

+1

啊,我錯過了減號在這個問題中,現在已經修正了,順便說一句,你在這裏有一個bug,在一個像「3.-1」這樣的字符串中,你不會匹配'「-1」' –