Niels Kristian
Niels Kristian

Reputation: 8845

Match all control characters but line break \n

Is there a way to write a regex that matches any control character except the line break "\n"?

I can write a regex to catch any of the control characters like so:

/\p{Cc}/

Upvotes: 0

Views: 445

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110725

str = "Q\cA\n\cD%\cH\n"       #=> "Q\u0001\n\u0004%\b\n"

str.gsub(/[^\p{Cc}]|\n/, '')  #=> "\u0001\u0004\b"

Note that

"\cH" #=> "\b"

Upvotes: 0

kfairns
kfairns

Reputation: 3057

This should do it:

/(?!\n)\p{Cc}/

Negative lookahead, shouldn't match line breaks

Upvotes: 6

Related Questions