java - 如何检查字符串是否匹配特定格式?
问题描述
我想了解如何检查字符串格式是否匹配
“111 + 222”
使用这样的字符串,格式应该是
(double type number)+(white space)+(operand(+,-,*,/,^))+(white space)+(double type number)
我知道我应该使用匹配来做到这一点,但我该如何处理这个与空白?
解决方案
是的,您可以使用模式匹配器或字符串匹配。
public static void main(String[] args) throws Exception {
String pattern = "-?[\\d\\.]{3,4}\\s[+\\-*/^]\\s-?[\\d\\.]{3,4}";
System.out.println(matchWithPatternMatcherCompile(pattern, "111 + 222")); // True
System.out.println(matchWithPatternMatcher(pattern, "111 + 222")); // True
System.out.println(matchWithStringRegex(pattern, "111 + 222")); // True
System.out.println(matchWithPatternMatcherCompile(pattern, "111 + -2.22")); // True
System.out.println(matchWithPatternMatcher(pattern, "11.1 + 222")); // True
System.out.println(matchWithStringRegex(pattern, "-111 + 222")); // True
}
private static boolean matchWithStringRegex(String regex, String input) {
return input.matches(regex);
}
private static boolean matchWithPatternMatcherCompile(String regex, String input) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
return matcher.matches();
}
private static boolean matchWithPatternMatcher(String regex, String input) {
return Pattern.matches(regex, input);
}
推荐阅读
- java - 我们如何让 Jframe 像 taksbar 中的 Skype 消息一样闪烁?
- java - 无法启动 chrome(版本 67)窗口 7 64 位
- xslt - XSLT - 显示每行上的所有节点数据(应该在不同的节点/行上拆分)
- java - 无法在 Hibernate 中运行一些时间 SQL 查询
- python - 如何让您的列表在 25 个字母后取下一个字符?
- ruby-on-rails - Rails 中的高级路由:与设计助手混合的约束
- laravel-5 - 如何将 laravel 5.4 部署到生产服务器?
- python - 使用 mayavi python 为 points3d 中的每个点分配颜色
- selenium - 无法使用 selenium 3.0.1 和 firefox 版本 61.0.1 调用 firefox gecko 驱动程序 0.20.1
- java - Android - 神秘权限出现在构建清单中