You need to also match the following newline (and possible carriage return), so instead your pattern would look like r"mod two;
?
?"
. The newline is optional, as otherwise it won't match if "mod two;"
is the last line in the file.
If you also want to support e.g. " mod two; "
, i.e. extra horizontal whitespace. Then you can use [ ]*
before and after, to optionally match zero-to-many spaces or tabs. To ensure that matching is done from the start of the line, you could use ^
, which requires enabling multi-line mode with (?m)
. All in all, the final pattern could look like this:
r"(?m)^[ ]*mod two;[ ]*
?
?"
Note that you can't use s*
in place of [ ]*
as s
also matches newlines. Thereby if mod two;
was surrounded by blank lines, then these would be trimmed too.
I'm assuming you're using regex, because you want to do some more complex matching and substitution later. However, if not then you could instead use lines()
, filter()
, collect()
and then join()
.
let file_contents = file_contents
.lines()
.filter(|&line| line.trim() != "mod two;")
.collect::<Vec<_>>()
.join("
");
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…