2013-03-22 12 views
10

mam podane ciąg znaków, który może zawierać zarówno tekst jak i danych numerycznych:wyodrębnić dane liczbowe z ciągiem w Groovy

Przykłady:

"100 funtów" "Myślę 173 lbs" „73 funtów. "

Poszukuję czystej metody wyodrębniania tylko danych liczbowych z tych ciągów.

Oto co mam obecnie robi się rozebrać odpowiedź:

def stripResponse(String response) { 
    if(response) { 
     def toRemove = ["lbs.", "lbs", "pounds.", "pounds", " "] 
     def toMod = response 
     for(remove in toRemove) { 
      toMod = toMod?.replaceAll(remove, "") 
     } 
     return toMod 
    } 
} 

Odpowiedz

20

można użyć findAll następnie przekonwertować wyniki do liczby całkowite:

def extractInts(String input) { 
    input.findAll(/\d+/)*.toInteger() 
} 

assert extractInts("100 pounds is 23" ) == [ 100, 23 ] 
assert extractInts("I think 173 lbs" ) == [ 173 ] 
assert extractInts("73 lbs."   ) == [ 73 ] 
assert extractInts("No numbers here"  ) == [] 
assert extractInts("23.5 only ints"   ) == [ 23, 5 ] 
assert extractInts("positive only -13") == [ 13 ] 

Jeśli potrzebujesz dziesiętne i liczby ujemne, możesz użyć bardziej złożonego wyrażeń regularnych:

def extractInts(String input) { 
    input.findAll(/-?\d+\.\d*|-?\d*\.\d+|-?\d+/)*.toDouble() 
} 

assert extractInts("100 pounds is 23" ) == [ 100, 23 ] 
assert extractInts("I think 173 lbs" ) == [ 173 ] 
assert extractInts("73 lbs."   ) == [ 73 ] 
assert extractInts("No numbers here" ) == [] 
assert extractInts("23.5 handles float") == [ 23.5 ] 
assert extractInts("and negatives -13" ) == [ -13 ] 
+0

rozwiązanie, które skończyło się na wdrażaniu na podstawie opinii powyżej, chcę tylko zgarnij pierwszą liczbę (jeśli są wielokrotności, unieważniam odpowiedź). Dzięki @tim_yates! 'def extractNumericData (odpowiedź String) { if (odpowiedź) { def numberList = response.findAll (/[0-9]+.[0-9]*|[0-9]*.[0-9 ] + | [0-9] + /) if (numberList.size() == 1) { powrotu numberList.get (0), a BigDecimal } else { powrotu -1 } } } ' –

1

Po dodaniu ing poniższą metodę numbersFilter poprzez metaklasa, można nazwać to w następujący sposób:

assert " i am a positive number 14".numbersFilter() == [ 14 ] 
assert " we 12 are 20.3propaged 10.7".numbersFilter() == [ 12,20.3,10.7 ] 
assert " we 12 a20.3p 10.7 ,but you can select one".numbersFilter(0) == 12 
assert " we 12 a 20.3 pr 10.7 ,select one by index".numbersFilter(1) == 20.3 

Dodaj ten kod jako Bootstrap

String.metaClass.numbersFilter={index=-1-> 
      def tmp=[]; 
      tmp=delegate.findAll(/-?\d+\.\d*|-?\d*\.\d+|-?\d+/)*.toDouble() 
      if(index<=-1){ 
       return tmp; 
      }else{ 
       if(tmp.size()>index){ 
        return tmp[index]; 
       }else{ 
        return tmp.last(); 
       } 
      } 

} 
Powiązane problemy