Java正则-String.matches的坑
来源:互联网 发布:vb.net 选择文件夹 编辑:程序博客网 时间:2024/06/03 19:33
Java正则-String.matches的坑
我想用String.matches匹配一行之中是否有特定的子串,结果死活出不来,我也在好多在线正则匹配的网上测试了,我正则表达式写的正确。查询了半天才知道,用String.matches匹配的正则,会在正则表达式前后加上^ $,是匹配整个大字符串是否满足正则表达式,而不会匹配到其中满足条件的子串!
//我的想法是以下2种都会成功匹配,其实是错误的//以下2种的正则"abc"相当于"^abc$",所以结果falseboolean a = "abcd".matches("abc");boolean b =Pattern.matches("abc", "abcd");System.out.println(a);//falseSystem.out.println(b);//false//而这种方法就能成功匹配出abcd中的abcPattern p=Pattern.compile("abc"); Matcher m=p.matcher("abcd"); while(m.find()){ System.out.println(m.group());//abc }
不解的是java api中Pattern.matches是这样说明的
public static boolean matches(String regex,
CharSequence input)
Compiles the given regular expression and attempts to match the given input against it.
An invocation of this convenience method of the formPattern.matches(regex, input);
behaves in exactly the same way as the expression
Pattern.compile(regex).matcher(input).matches()
If a pattern is to be used multiple times, compiling it once and reusing it will be more efficient than invoking this method each time.
Parameters:
regex - The expression to be compiled
input - The character sequence to be matched
官网说表现是一样的,可结果肯定是不一样的啊。
参考链接:stackoverflow
- Java正则-String.matches的坑
- String.matches()的用法/正则表达式
- java中正则表达式运用实例(用String类的matches方法演示)
- java中正则表达式运用实例(用String类的matches方法演示)
- Java String matches()方法
- String的matches使用方法
- String.matches()的用法
- String.matches()的用法
- String.matches()的用法
- String.matches()的用法
- java正则表达式之matches
- JAVA正则表达式,matcher.find()和 matcher.matches()的区别
- JAVA正则表达式,matcher.find()和 matcher.matches()的区别
- JAVA正则表达式,matcher.find()和 matcher.matches()的区别
- JAVA正则表达式,matcher.find()和 matcher.matches()的区别
- JAVA正则表达式,matcher.find()和 matcher.matches()的区别
- JAVA正则表达式,matcher.find()和 matcher.matches()的区别
- Java中正则Matcher类的matches()、…
- 进入java 行业的开山之作
- (转)FPS科普
- 1055. The World's Richest (25)-排序(易)
- 纯css3实现美化复选框和手风琴效果(详细)
- 0x3f3f3f3f 编程中无穷大常量的设置技巧
- Java正则-String.matches的坑
- 富爸爸--财务自由之路4
- 1031. Hello World for U
- Unity中国象棋(二)——走棋
- uva 10763 交换学生
- 编程模拟自然(九):元胞自动机
- 如何计算程序或某函数运行时间
- pcap文件格式
- java使用io流技术替换LOL英雄的皮肤