i trying match string integer or double then, if not match, want remove invalid characters make string valid integer or double (or empty string). far, have print 15- not valid
string anchorguyfield = "15-"; if(!anchorguyfield.matches("-?\\d+(.\\d+)?")){ //match integer or double anchorguyfield = anchorguyfield.replaceall("[^-?\\d+(.\\d+)?]", ""); //attempt replace invalid chars... failing here }
you can use pattern() , matcher() validate if string suitable covertion int or 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); } } with:
anchorguyfield = anchorguyfield.replaceall("[^-?\\d+(.\\d+)?]", ""); you delete content wanted match string, insted of 15 15-, should -
Comments
Post a Comment