Java 正则表达式不匹配 [英] Java Regex does not match
本文介绍了Java 正则表达式不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道这种问题经常被提出,但是我不明白为什么这个 RegEx 不匹配.我想检查行首是否有M".最后,我想要行尾的路径.这就是 startsWith() 不适合我的需求的原因.
I know that this kind of questions are proposed very often, but I can't figure out why this RegEx does not match. I want to check if there is a "M" at the beginning of the line, or not. Finaly, i want the path at the end of the line. This is why startsWith() doesn't fit my Needs.
line = "M 72208 70779 koj src\com\company\testproject\TestDomainf1.java";
if (line.matches("^(M?)(.*)$")) {}
我也试过另一种方法:
Pattern p = Pattern.compile("(M?)");
Matcher m = datePatt.matcher(line);
if (m.matches()) {
System.out.println("yay!");
}
if (line.matches("(M?)(.*)")) {}
谢谢
推荐答案
您不需要正则表达式.只需使用 String#startsWith(String)
You dont need a regex for that. Just use String#startsWith(String)
if (line.startsWith("M")) {
// code here
}
或者使用 <代码>String#toCharArray():
if (line.length() > 0 && line.toCharArray()[0] == 'M') {
// code here
}
在您编辑了从输入字符串获取路径的要求之后.
After your edited requirement to get path from input string.
您仍然可以避免使用正则表达式并使用如下代码:
You still can avoid regex and have your code like this:
String path="";
if (line.startsWith("M"))
path = line.substring(line.lastIndexOf(' ')+1);
System.out.println(path);
输出:
src\com\company\testproject\TestDomainf1.java
这篇关于Java 正则表达式不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文