Java字符串常用操作

String字符串

查找单引号里的内容

// String regex = "'([^']*)'";
// 使用懒惰量词 *? 
String regex = "'(.*?)'";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(msg);
while (matcher.find()) {
    para.put("parameter", matcher.group(1));//直接用group()会带出单引号
}

判断字符串是否是数字

  • 正则表达式

    /**
         * 利用正则表达式判断字符串是否是数字
         * @param str
         * @return
         */
        public boolean isNumeric(String str){
               Pattern pattern = Pattern.compile("[0-9]*");
               Matcher isNum = pattern.matcher(str);
               if( !isNum.matches() ){
                   return false;
               }
               return true;
        }
  • common包

    org.apache.commons.lang.StringUtils;
    ​
    boolean isNunicodeDigits=StringUtils.isNumeric("aaa123456789");
    ​
    http://jakarta.apache.org/commons/lang/api-release/index.html下面的解释:
    ​
    public static boolean isNumeric(String str)Checks if the String contains only unicode digits. A decimal point is not a unicode digit and returns false.
    ​
    null will return false. An empty String ("") will return true.
    ​
    StringUtils.isNumeric(null)   = false
    ​
    StringUtils.isNumeric("")     = true
    ​
    StringUtils.isNumeric(" ")   = false
    ​
    StringUtils.isNumeric("123") = true
    ​
    StringUtils.isNumeric("12 3") = false
    ​
    StringUtils.isNumeric("ab2c") = false
    ​
    StringUtils.isNumeric("12-3") = false
    ​
    StringUtils.isNumeric("12.3") = false

字符串、数字互相转换

  • string 和int之间的转换

    string转换成int :Integer.valueOf("12")

    int转换成string : String.valueOf(12)

  • char和int之间的转换

    首先将char转换成string

    String str=String.valueOf('2')

    Integer.valueof(str) 或者Integer.PaseInt(str)

    区别:Integer.valueof返回的是Integer对象,Integer.paseInt返回的是int

猜你喜欢

转载自blog.csdn.net/cadn_jueying/article/details/83012885