Skip to content

Is this the correct way to use regex.replace? #911

Answered by BurntSushi
frederikhors asked this question in Q&A
Discussion options

You must be logged in to vote

Here's the first problem that pops out at me:

r"^[ \t]+|[ \t]+$|([ \t]){2,}/mg"

Why are you adding /mg to the regex? That only works for Javascript regex literals. This is Rust. Rust does not have regex literals. The docs have several examples for how to set flags. In this case, you'd want (?m)^[ \t]+|[ \t]+$|([ \t]){2,}. The g flag is irrelevant in Rust, and only exists in Javascript because of some oddities with its regex API.

reg.replace(input, "$1").to_string()

This is your second problem. From the docs of Regex::replace:

Replaces the leftmost-first match with the replacement provided.

It only replaces the first match. It looks like you want all matches replaced. So you should s…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@frederikhors
Comment options

@BurntSushi
Comment options

Answer selected by frederikhors
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants