简体   繁体   English

Java Regex:匹配行首

[英]Java Regex: Matching the beginning of a line

I am reading through a number of text files that are a dump of e-mail messages. 我正在阅读大量文本文件,这些文本文件是电子邮件的转储。 I am trying to check if the line I am reading starts with "Cc:". 我正在尝试检查我正在读取的行是否以“抄送:”开头。 For example I would want to match the following example line "Cc:\\temail1@example.com; email2@exmaple.com". 例如,我想匹配以下示例行“ Cc:\\ temail1@example.com; email2@exmaple.com”。

The code that I am using looks like this: 我正在使用的代码如下所示:

Pattern pattern = Pattern.compile("^Cc\\:");
line = reader.readLine();

if (pattern.matcher(line).matches()) {
   System.out.println(line);
}

Any idea why this is not matching? 知道为什么这不匹配吗?

There's nothing wrong with your regex per se (although you have unnecessarily escaped the colon, but bit will still work), but the reason it's not working is that in java (unlike most other popular languages) matches() must match the whole string. 正则表达式本身没有什么问题(尽管您不必要地逃脱了冒号,但仍然可以工作),但是不起作用的原因是在Java中(与大多数其他流行语言不同) matches()必须匹配整个字符串。 Change your regex to "Cc:.*" . 将您的正则表达式更改为"Cc:.*" Note how in java you don't need the ^ or $ because they are implied due to having to match the whole string. 请注意,在Java中您不需要^或$,因为由于必须匹配整个字符串而隐含了它们。

However, for a simpler case-insensitive check using regex: 但是,对于使用正则表达式的更简单的不区分大小写的检查:

if (line.matches("(?i)cc:.*")) // note the .*

Or without regex: 或不使用正则表达式:

if (line.toLowerCase().startsWith("cc:"))

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

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