我正在尝试将字符串匹配到任何整数或双精度数,如果不匹配,我想删除所有无效字符以使字符串成为有效的整数或双精度(或空字符串)。到目前为止,这是我所拥有的,但是它将打印15-这是无效的

String anchorGuyField = "15-";

if(!anchorGuyField.matches("-?\\d+(.\\d+)?")){ //match integer or double
        anchorGuyField = anchorGuyField.replaceAll("[^-?\\d+(.\\d+)?]", ""); //attempt to replace invalid chars... failing here
    }

最佳答案

您可以使用Pattern()Matcher()来验证字符串是否适合覆盖int或double:

public class Match{
    public static void main(String[] args){
        String anchorGuyField = "asdasda-15.56757-asdasd";

        if(!anchorGuyField.matches("(-?\\d+(\\.\\d+)?)")){ //match integer or double
            Pattern pattern = Pattern.compile("(-?\\d+(\\.\\d+)?)");
            Matcher matcher = pattern.matcher(anchorGuyField);
            if(matcher.find()){
            anchorGuyField = anchorGuyField.substring(matcher.start(),matcher.end());
            }
        }
        System.out.println(anchorGuyField);
    }
}


与:

anchorGuyField = anchorGuyField.replaceAll("[^-?\\d+(.\\d+)?]", "");


您实际上从字符串中删除了要匹配的内容,从15中插入了15-,您应该只得到-

09-11 18:35