2017-09-02 48 views
0

如何在输出+ -12aba到+ -12中使用正则表达式,也就是说,除了数字和负号以外。如何在输出中使用正则表达式+ -12aba到+ -12

public class LeetCode8 { 
public static int myAtoi(String str) { 
    str = str.replaceAll("\\s+", ""); 
    System.out.println(str); 
    if (!str.matches("[0-9]+")&&!str.matches("\\+[0-9]+")&&!str.matches("\\-[0-9]+")) { 
     return 0; 
    } 
    str.replaceAll("", "0"); 
    if (str.length() > 10) { 
     return 0; 
    } 
    long a = Long.valueOf(str); 
    if (a > Integer.MAX_VALUE) { 
     return 0; 
    } 
    return (int) a; 
} 

public static void main(String[] args) { 
    int i = myAtoi("-12aba"); 
    System.out.println(i); 
    //i want wo output -12 
} 

}

+4

这里是你的代码? –

+0

没有代码,但我想问的是如何使用正则表达式将字符串+ -12aba转换为+ -12。 – Lizumi

+1

所以你还没有尝试过任何东西! –

回答

0

也许试试这个:

private int myAtoi(String input){ 
    Pattern p = Pattern.compile("(\\-|\\+)\\d+"); 
    Matcher m = p.matcher(input); 

    if (!m.find()) 
     return 0; 
    else 
     return Integer.valueOf(m.group()); 
}