Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex matching whole line starting with an exclamation mark

Tags:

regex

ruby

I'm trying to match whole line of text starting from ! with regex.

I made something like this: /(!\w+\s+\S+)/ig which is pretty close, but only for 2 words. I would like to match words upto new line. Also I see problem with spoiler in the middle of sentence.

Live example: http://www.rubular.com/r/MXmholsDwE

like image 691
Szmerd Avatar asked May 05 '16 13:05

Szmerd


People also ask

What does exclamation mark do in regex?

Search without case sensitivity. If an exclamation mark (!) occurs as the first character in a regular expression, all magic characters are treated as special characters. An exclamation mark is treated as a regular character if it occurs anywhere but at the very start of the regular expression.

How do you match a full expression in regex?

To run a “whole words only” search using a regular expression, simply place the word between two word boundaries, as we did with ‹ \bcat\b ›. The first ‹ \b › requires the ‹ c › to occur at the very start of the string, or after a nonword character.

What does \b mean in regex?

A word boundary \b is a test, just like ^ and $ . When the regexp engine (program module that implements searching for regexps) comes across \b , it checks that the position in the string is a word boundary.

What does \f mean in regex?

\f stands for form feed, which is a special character used to instruct the printer to start a new page.


2 Answers

You just need

^!.*

See the updated regex demo

The ^ matches the start of a line (in Ruby), ! will match a literal ! and .* will match zero or more characters other than a newline (if you are using Ruby, which I assume from your use of the rubular Web site).

If you are using a regex flavor other than Ruby, like JS, or PHP, or .NET, you need to specify the /m - MULTILINE - modifier (e.g. /^!.*/gm in JavaScript).

like image 172
Wiktor Stribiżew Avatar answered Oct 19 '22 12:10

Wiktor Stribiżew


If you want to match everything to the end of the line:

/(!.+)/

If you want to make sure that it follows the format !word---:

/!\w.+/
like image 5
amphetamachine Avatar answered Oct 19 '22 11:10

amphetamachine