且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java 正则表达式不匹配

更新时间:2022-06-25 22:07:11

您不需要正则表达式.只需使用 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