我有这个转换器,用于从组合框中获取或设置标签:
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 :(得分:1)
试试这个
String s="45 - Next";// the string from the box
int num=Integer.parseInt(s.split("-")[0].trim());
答案 1 :(得分: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);
}