`
baiyangliu
  • 浏览: 28351 次
文章分类
社区版块
存档分类
最新评论

Java正则表达式

 
阅读更多
public class StringUtil {
	/**
	 * 去除字符串中的特殊字符
	 * 
	 * @param string
	 * @return
	 */
	public static String clean(String string) {
		String regEx = "[^A-Za-z\\d\\u4E00-\\u9FA5]+";
		return clean(string, regEx);
	}

	public static String clean(String string, String regEx) {
		Pattern pattern = Pattern.compile(regEx);
		Matcher matcher = pattern.matcher(string);
		return matcher.replaceAll("").trim();
	}

	/**
	 * 返回所有匹配的字符串
	 * 
	 * @param regEx
	 *            正则表达式
	 * @param string
	 */
	public static List<String> getMatchedStrings(String regEx, String string) {
		List<String> result = new ArrayList<String>();
		Pattern pattern = Pattern.compile(regEx);
		Matcher matcher = pattern.matcher(string);
		while (matcher.find()) {
			result.add(matcher.group());
		}
		return result;
	}

	/**
	 * 检查是否为所需格式
	 * 
	 * @param string
	 * @return
	 */
	public static boolean isValid(String string) {
		String regEx = "[A-Za-z\\d\\u4E00-\\u9FA5]+";
		return isValid(string, regEx);
	}

	public static boolean isValid(String string, String regEx) {
		Pattern pattern = Pattern.compile(regEx);
		Matcher matcher = pattern.matcher(string);
		if (matcher.matches()) {
			return true;
		}
		return false;
	}
}

验证数字(正负数、小数)

^[\\+-]?\\d|[\\+-]?\\d+\\.\\d+$



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics