Java Regex does not match

java, regex

Solution

You dont need a regex for that. Just use `String#startsWith(String)`

if (line.startsWith("M")) {
    // code here
}

OR else use `String#toCharArray()`:

if (line.length() > 0 && line.toCharArray()[0] == 'M') {
    // code here
}

EDIT: 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);

OUTPUT:

src\com\company\testproject\TestDomainf1.java

Problem

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?)(.*)$")) {} ``` I've also tried the other way out: ``` Pattern p = Pattern.compile("(M?)"); Matcher m = datePatt.matcher(line); if (m.matches()) { System.out.println("yay!"); } if (line.matches("(M?)(.*)")) {} ``` Thanks

Original source