2013-12-22 60 views
-2

我有這個轉換器是用來獲取或從組合框中設置標籤:獲取一些

public class GroupConverter extends StringConverter<ListGroupsObj> 
{ 

    @Override 
    public String toString(ListGroupsObj obj) 
    { 
     return obj.getGroupId() + " - " + obj.getGroupName(); 
    } 

    @Override 
    public ListGroupsObj fromString(String obj) 
    { 

     Scanner fi = new Scanner(obj); 
     //anything other than alphanumberic characters, 
     //comma, dot or negative sign is skipped 
     fi.useDelimiter("[^\\p{Alnum},\\.-]"); 
     while (true) 
     { 
      if (fi.hasNextInt()){ 
       //System.out.println("Int: " + fi.nextInt()); 
       return ListGroupsObj.newInstance().groupId(fi.nextInt()); 
      } 
      break;      
     } 

     //TODO when you type for example "45 - NextGroup" you want to take only tyhe number" 
     return ListGroupsObj.newInstance().groupId(fi.nextInt()); 
    } 

} 

例如,當我鍵入「45 - NextGroup」我想只得到數值。你能幫我實施嗎?

+0

如果obj.getGroupId()返回一個字符串,你可以簡單地做'的Integer.parseInt(obj.getGroupId());' – Kon

+0

到http類似://計算器.com/questions/2367381/extract-numbers-from-a-string-java – MariuszS

+0

我更新了代碼。 –

回答

1

試試這個

String s="45 - Next";// the string from the box 
int num=Integer.parseInt(s.split("-")[0].trim()); 
1
 String s="45 - Next"; 
     String reg = "[0-9]+"; 
     Pattern pattern = Pattern.compile(reg); 
     Matcher matcher = pattern.matcher(s); 
     while(matcher.find()) { 
      String numString = matcher.group(); 
      int num = Integer.parseInt(numString); 
      System.out.println(num); 
     }