0

I am trying to understand why a regular expression ending with "|" (or simply "|" itself) will find a matching substring with start index 0 and end "offset after the last character matched (as per JavaDoc for Matcher)" 0.

The following code demonstrates this:

public static void main(String[] args) {

    String regExp = "|";
    String toMatch = "A";
    Matcher m = Pattern.compile(regExp).matcher(toMatch);
    System.out.println("ReqExp: " + regExp + 
            " found " + toMatch + "(" + m.find() + ") " +  
            " start: " + m.start() +
            " end: " + m.end());

}

Output is:

ReqExp: | found A(true)  start: 0 end: 0

I'm confused by the fact that it is even a valid regular expression. And further confused by the fact that start and end are both 0.

Hoping someone can explain this to me.

1 Answer 1

4

The pipe in a regular expression means "or." So your regular expression is basically "(empty string) or (empty string)". It successfully finds an empty string at the beginning of the string, and an empty string has a length of 0.

Sign up to request clarification or add additional context in comments.

1 Comment

If someone is confused with (nothing) then maybe it will be clearer if we describe it as empty string "" (one with length 0). In other words we can assume that "|" regex is same as ""+"|"+"" so empty string OR empty string. Since every string can be represented as someString <==> ""+someString we can assume that each string starts (and also ends) with empty string at position 0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.