简体   繁体   中英

Start of the line regex usage in java Pattern.matches method?

I am a little bit confused about the ^ symbol in regex.

From what I read online it means : "Finds regex that must match at the beginning of the line."

I read about the example presented here : https://regexone.com/lesson/line_beginning_end

" In the example above, we can use the pattern ^success to match only a line that begins with the word "success", but not the line Error: unsuccessful operation

My confusion comes from the fact that ^success will only match with the string "success" right ? So what is the point of ^ In the examples below ? I would have expect the second to also be true, based on the description of the ^ symbol.

System.out.println(Pattern.matches("^success","success"));  // true
System.out.println(Pattern.matches("^success","success is good"));  // false

Can anyone give me any clear examples with this ^ symbol used in regex?

You are right, ^success only matches the string "success".
But ^success still is a pattern to be found in a string like "success is good".

You could check...

System.out.println(Pattern.matches("^success.*","success is good"));

...which should be true, because it matches strings that start with "success" and contain any more characters.
OR you can try to find the pattern ^success in a string. It's a problem of terminology. A pattern matches a string only if it matches the whole string completely . To find a pattern as part of a string (so a substring of it matches the pattern) is a different thing!

A full match of a string also implies ^ and $ (for beginning and end of the string) in the pattern, because the string has to match from beginning to end (thanks to @Pshemo for pointing that out!).

Also see: Using Java to find substring of a bigger string using Regular Expression

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM