简体   繁体   English

Java Pattern.matches方法中的行正则表达式用法的开头?

[英]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 我阅读了此处提供的示例: 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 “在以上示例中,我们可以使用模式^success来仅匹配以单词“ success”开头的行,而不匹配该行Error: unsuccessful operation

My confusion comes from the fact that ^success will only match with the string "success" right ? 我的困惑来自^success仅与字符串“ success”匹配的事实吗? 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". 没错, ^success匹配字符串“ success”。
But ^success still is a pattern to be found in a string like "success is good". 但是^success仍然是在“ 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. ...这应该是正确的,因为它匹配以“ success”开头且包含更多字符的字符串。
OR you can try to find the pattern ^success in a string. 或者,您可以尝试在字符串中找到模式^success 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!). 字符串的完全匹配还意味着模式中的^$ (用于字符串的开头和结尾),因为字符串必须从头到尾匹配(感谢@Pshemo指出!)。

Also see: Using Java to find substring of a bigger string using Regular Expression 另请参见: 使用Java使用正则表达式查找较大字符串的子字符串

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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