正则表达式 - Java 以 * 开头并以换行符 (\n) 结尾
regex - Java starts with * and ends with a newline (\n)
基本上是这样的:
int abc = 10;
* this is a comment
所以,我只想找到 * this is a comment
以便我可以将其从字符串中删除。我已经尝试了一些示例,但它似乎不起作用。这个想法基本上是从 *
开始,然后是单词、数字或符号的任意组合(任何真正的东西),最后以换行符 (\n)
结束。
谢谢。
模式 ^\*.*$
应该适用于此:
String line = "Not a comment\n* This is a comment\n*This is also a comment\n";
line += "Not a * comment.";
String pattern = "^\*.*$";
Pattern r = Pattern.compile(pattern, Pattern.MULTILINE);
Matcher m = r.matcher(line);
while (m.find( )) {
System.out.println("Found value: " + m.group(0) );
}
Found value: * This is a comment
Found value: *This is also a comment
这里不多做解释,只是说*
是一个正则元字符,如果要把它当作字面量来使用,那么需要用反斜杠转义。
在这种情况下,IMO 的正则表达式有点矫枉过正。用“\n”分隔行,然后对每一行简单地用 line.startsWith("*")
检查它就可以进行过滤。
基本上是这样的:
int abc = 10;
* this is a comment
所以,我只想找到 * this is a comment
以便我可以将其从字符串中删除。我已经尝试了一些示例,但它似乎不起作用。这个想法基本上是从 *
开始,然后是单词、数字或符号的任意组合(任何真正的东西),最后以换行符 (\n)
结束。
谢谢。
模式 ^\*.*$
应该适用于此:
String line = "Not a comment\n* This is a comment\n*This is also a comment\n";
line += "Not a * comment.";
String pattern = "^\*.*$";
Pattern r = Pattern.compile(pattern, Pattern.MULTILINE);
Matcher m = r.matcher(line);
while (m.find( )) {
System.out.println("Found value: " + m.group(0) );
}
Found value: * This is a comment
Found value: *This is also a comment
这里不多做解释,只是说*
是一个正则元字符,如果要把它当作字面量来使用,那么需要用反斜杠转义。
在这种情况下,IMO 的正则表达式有点矫枉过正。用“\n”分隔行,然后对每一行简单地用 line.startsWith("*")
检查它就可以进行过滤。