-4

Java,如何通过正则表达式获取最后一个字符?例如,像“abcdefff”这样的字符串,我想找出“efff”或“ff”......

4

2 回答 2

5

If you want the last n characters of a string, use substring().

String lastChars = str.substring(str.length() - 3);

If you must match only a single character, use Pattern with the regex n{3}$.

Pattern regex = Pattern.compile("n{3}$");
Matcher matches = regex.matcher(str);

Generally, you'd only use a regex if the other string methods would become too unwieldy. If you simply want to grab the last any characters, I'd always use substring(), as to me, it's clearer to parse mentally.

于 2013-08-15T04:13:24.417 回答
0

你也可以这样做

    String str="abcdefff";
    if(str.length()>2){
    System.out.println(str.substring(str.length()-2));
    }else{
    System.out.println(str);
    }
于 2013-08-15T04:22:28.617 回答