博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
日常验证字符串方法
阅读量:4494 次
发布时间:2019-06-08

本文共 10730 字,大约阅读时间需要 35 分钟。

package com.yxz.framework.utils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.IOUtils;

public class StringUtil {

private static final String MOBILE_REG = "^(13[0-9]|14[0-9]|15[0-9]|18[0-9]|17[0-9])\\d{8}$";
private static final String EMAIL_REG = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
/**
* 生成随机字符串
* @param random
* @param len
* @return
*/
public static String getRandomString( int random, int len ){
java.util.Random rd = new java.util.Random();
StringBuffer sb = new StringBuffer();
int rdGet; // 取得随机数
char ch;
for ( int i = 0 ; i < len; i ++ ){
rdGet = Math.abs(rd.nextInt()) % 10 + 48 ; // 产生48到57的随机数(0-9的键位值)
//rdGet=Math.abs(rd.nextInt())%26+97; // 产生97到122的随机数(a-z的键位值)
ch = ( char ) rdGet;
sb.append( ch );
}
return sb.toString();
}
/**
* 截取字符串截取的字符用...显示
*
* @return
*/
public static String subStringStr(String str,int size)
{
if(isEmptyString(str))
return "";
if(str.length()<size)
return str;
String lastString = str.substring(0,size)+"...";
return lastString;
}
/**
* 截取字符串
*
* @return
*/
public static String subStringStrNoSuffix(String str,int size)
{
if(isEmptyString(str))
return "";
if(str.length()<size)
return str;
String lastString = str.substring(0,size);
return lastString;
}
/**
* 判断传入的字符串是否为空串
*
* @return
*/
public static boolean isEmptyString(String str) {
return str == null ? true : str.trim().equals("") ? true : false;
}
/**
* Float转换成String
* @param n 小数点后保留几位
* @param f 要转化的数
* @return
*/
public static String getPercent(int n,Float f){
java.text.NumberFormat nf = java.text.NumberFormat.getPercentInstance();
nf.setMinimumFractionDigits(n);
String str = nf.format(f);
return str;
}
/**
* 判断传入的字符串是否为空串,如果是null的就替换为""空字符串.
*
* @return
*/
public static String replaceNullStr(String str) {
if(str==null){
return "";
}
if(!isEmptyString(str)){
if("null".equals(str)){
str=str.replace("null", "");
return str;
}else{
return str;
}
}else{
return str;
}
}
/**
* 验证是否是有效的手机号
*
* @param mobile 手机号
* @return
*/
public final static boolean validMobileNumber(final String mobile) {
if (isEmptyString(mobile)) {
return false;
}

Pattern pattern = Pattern.compile(MOBILE_REG);

if (!pattern.matcher(mobile).matches()) {

return false;
}
return true;
}
/**
* 校验是否是有效的邮件地址
*
* @param email 邮箱地址
* @return 有效则返回真,否则返回假
*/
public static boolean validEmail(final String email) {
if (isEmptyString(email)) {
return false;
}
Pattern pattern = Pattern.compile(EMAIL_REG);
if (!pattern.matcher(email).matches()) {
return false;
}
return true;
}
/**
* 校验有效的名称
* @param nickName 昵称
* @return 返回真
*/
public static boolean validUserName(final String userName) {
boolean isAllDigit =userName.matches("[0-9]+");
if(isAllDigit)
{
//用户名不能为纯数字
return false;
}
return true;
}
/**
* 去除字符串首尾出现的某个字符.
* @param source 源字符串.
* @param element 需要去除的字符.
* @return String.
*/
public static String trimFirstAndLastChar(String source,char element){
boolean beginIndexFlag = true;
boolean endIndexFlag = true;
do{
int beginIndex = source.indexOf(element) == 0 ? 1 : 0;
int endIndex = source.lastIndexOf(element) + 1 == source.length() ? source.lastIndexOf(element) : source.length();
source = source.substring(beginIndex, endIndex);
beginIndexFlag = (source.indexOf(element) == 0);
endIndexFlag = (source.lastIndexOf(element) + 1 == source.length());
} while (beginIndexFlag || endIndexFlag);
return source;
}
/**
* 转换成UTF-8编码
* @param str
* @return
*/
public static String toUTF8(String str){
if(!isEmptyString(str)){
try{
return new String(str.getBytes("iso8859-1"),"UTF-8");
}catch(Exception ex){
return "";
}
}
return "";
}
/**
* 屏蔽手机的方法
* @param source 手机号
* @return
*/
public static String hiddenMobile(String source) {
if (isEmptyString(source)) {
return "";
}
Pattern pattern = Pattern.compile("^1\\d{10}$");

if (pattern.matcher(source).matches()) {

return source.substring(0,3) + "****" + source.substring(7, 11);
} else {
return source;
}
}
/**
* 屏蔽邮箱的方法
* @param source 邮箱
* @return
*/
public static String hiddenEmail(String source) {
if (isEmptyString(source)) {
return "";
}
Pattern pattern = Pattern.compile(EMAIL_REG);
if (pattern.matcher(source).matches()) {
int splitIndex = source.indexOf("@");
String emailPrefix = source.substring(0, splitIndex);
if(emailPrefix.length() > 4)
{
source = source.substring(0, emailPrefix.length()-4) + "****" + source.substring(splitIndex);
}
else
{
source = source.substring(0, 1) + "****" + source.substring(splitIndex);
}
return source;
}
else
{
return source;
}
}
/**
* 屏蔽身份证号的方法
* @param source 身份证号
* @return
*/
public static String hiddenIDCard(String source)
{
if (isEmptyString(source)) {
return "";
}
if(source.length() > 8)
{
source = source.substring(0, source.length()-8) + "********";
}
else
{
source = source.substring(0, 1) + "********";
}
return source;
}
/**
* 反射输出实体类所有公共无入参的get和is方法名称和值--日志中使用
* @param object 实体类对象
* @return object属性名称名称及属性值
*/
public static String printParam(Object object){
if(object==null){
return "";
}
StringBuffer out=new StringBuffer();
try {
Class<?> clazz=object.getClass();
out.append(clazz.getSimpleName());
out.append(" [");
Method[] methods=clazz.getMethods();
for (Method method : methods) {
if(method.getName().indexOf("get")>=0){
Type [] types=method.getGenericParameterTypes();
if(types==null || types.length==0){
Method mtd = clazz.getMethod(method.getName(),new Class[]{});
Object value = mtd.invoke(object);
if(value!=null){
out.append(method.getName()+"="+value.toString()+",");
}
}
}
}
out.append("]");
} catch (Exception e) {
}
return out.toString();
}
/**
* 用变量值替换字符串模板中的变量
* @param template 模板
* @param varStart 变量开始字符串
* @param varEnd 变量结束字符串
* @param values 变量值
* @return
*/
public static String buildStringByTemplate(String template, String varStart, String varEnd, Map<String,String> values){
String s = template;
for(String key : values.keySet()){
s = s.replace(varStart + key + varEnd, values.get(key) == null?"":values.get(key));
}
return s;
}
/**
* 把字节数组保存为一个文件
*/
public static File getFileFromBytes(byte[] b, String outputFile) throws Exception{
BufferedOutputStream stream = null;
FileOutputStream fstream = null;
File file = null;
try{
file = new File(outputFile);
fstream = new FileOutputStream(file);
stream = new BufferedOutputStream(fstream);
stream.write(b);
} catch (Exception e){
throw e;
} finally{
IOUtils.closeQuietly(stream);
IOUtils.closeQuietly(fstream);
}
return file;
}
/**
* 隐藏姓名
* @param userName
* @return
*/
public static String hidenUserName(String userName) {
if(isEmptyString(userName)){
return userName;
}
return userName.substring(0, 1)+"**";
}
/**
* 处理 "null"
* @param value
* @return
*/
public static String coverNullStrValue(String value){
if ("null".equals(value)||value==null) {
return "";
}
return value;
}
/**
* 变换数组为字符串
* @param arr
* @return
*/
public static String arrToStr(String[] arr) {
String str = null;
if (arr != null) {
str = org.springframework.util.StringUtils.quote(org.springframework.util.StringUtils.arrayToDelimitedString(arr, "','"));
}
return str;
}
public static boolean isPinyin(String keyword){
Pattern p = Pattern.compile("([a-z|A-Z]*)");
Matcher m = p.matcher(keyword);
return m.matches();
}
/**
* 判断是否是数字(>=0 不包括负数)
* @param str
* @return
*/
public static boolean isNumber(String str){
if(isEmptyString(str)){
return false;
}
return str.matches("^\\d+");
}
/**
* 判断两个字符串的内容是否相同
* @param s1
* @param s2
*/
public static boolean isSame(String s1,String s2){
if(s1!=null){
return s1.equals(s2);
}else if(s2!=null){
return s2.equals(s1);
}else{
return true;
}
}

/**
* 设置地区地区编码
*
* @return
*/
public static Map<String, String> GetAreaCode() {
Map<String, String> areas = new HashMap<String, String>();
areas.put("11", "北京");
areas.put("12", "天津");
areas.put("13", "河北");
areas.put("14", "山西");
areas.put("15", "内蒙古");
areas.put("21", "辽宁");
areas.put("22", "吉林");
areas.put("23", "黑龙江");
areas.put("31", "上海");
areas.put("32", "江苏");
areas.put("33", "浙江");
areas.put("34", "安徽");
areas.put("35", "福建");
areas.put("36", "江西");
areas.put("37", "山东");
areas.put("41", "河南");
areas.put("42", "湖北");
areas.put("43", "湖南");
areas.put("44", "广东");
areas.put("45", "广西");
areas.put("46", "海南");
areas.put("50", "重庆");
areas.put("51", "四川");
areas.put("52", "贵州");
areas.put("53", "云南");
areas.put("54", "西藏");
areas.put("61", "陕西");
areas.put("62", "甘肃");
areas.put("63", "青海");
areas.put("64", "宁夏");
areas.put("65", "新疆");
areas.put("71", "台湾");
areas.put("81", "香港");
areas.put("82", "澳门");
areas.put("91", "国外");
return areas;
}

/**

* 判断字符串是否为数字
*
* @param str
* @return
*/
@SuppressWarnings("unused")
private static boolean isNumeric(String str) {
if(isEmptyString(str)){
return false;
}
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(str);
if (isNum.matches()) {
return true;
} else {
return false;
}
}

/**

* 功能:判断字符串是否为日期格式
*
* @param str
* @return
*/
public static boolean isDate(String strDate) {
if(isEmptyString(strDate)){
return false;
}
Pattern pattern = Pattern
.compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$");
Matcher m = pattern.matcher(strDate);
if (m.matches()) {
return true;
} else {
return false;
}
}
public static String getContent(Map<String,String> params) {
List<String> keys = new ArrayList<String>(params.keySet());
Collections.sort(keys);//对参数排序,已确保拼接的签名顺序正确
String prestr = "";
boolean first = true;
for (int i = 0; i < keys.size(); i++) {
String key = (String) keys.get(i);
String value = (String) params.get(key);
if (value == null || value.trim().length() == 0) {
continue;
}
if (first) {
prestr = prestr + key + "=" + value;
first = false;
} else {
prestr = prestr + "&" + key + "=" + value;
}
}
return prestr ;
}
public static String cutString2(int len,String source){
if(source.length()>=len){
return source.substring(0, len)+"… ";
}else{
return source;
}
}
public static String cutString(int len,String source){
if(source.length()>=len){
return source.substring(0, len)+"… ";
}else{
return source;
}
}

}

转载于:https://www.cnblogs.com/tanxd/p/5364024.html

你可能感兴趣的文章
hdfs集群(hadoop_03)
查看>>
奇虎360安全牛人全球挑战赛无线部…
查看>>
Uploadify V3.2.1 上传文件报404 Not Found问题解决
查看>>
cocos2d-x发生undefined reference to `XX'异常 一劳永逸解决的方法
查看>>
Android 之 GridView具体解释
查看>>
SQL Server里实现 数据导入导出
查看>>
7-2 寻找大富翁 (25 分)
查看>>
word转html 压缩图片网站
查看>>
阿拉丁工作内容
查看>>
C#向pdf 添加水印
查看>>
HDU1754 I hate it 线段树
查看>>
POJ 3744 Scout YYF I 概率DP+矩阵快速幂 好题
查看>>
spring ioc---参数注入
查看>>
[React] Cleanly Map Over A Stateless Functional Component with a Higher Order Component
查看>>
[TypeStyle] Style CSS pseudo elements with TypeStyle
查看>>
算是自己真正意义上开发的程序吧--库存管理系统
查看>>
【翻译】Pro.Silverlight.5.in.CSharp.4th.Edition - 第四章 依赖属性和路由事件 01
查看>>
用Python实现-->冒泡排序和选择排序
查看>>
hdu 3631 多源最短路
查看>>
JQuery选择器大全
查看>>