Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case insensitive for part of the regex?

Tags:

regex

ruby

I have a regex where part of the regex should be case insensitive.

Example:

/Guest post by ([A-Z][a-z]+\s[A-Z][a-z]+)/

"Guest post by" should be case insensitive, but the 2nd half obviously needs to be case sensitive as it's looking for a first name + last name, with the first letter capitalized in each.

So if I do

/Guest post by ([A-Z][a-z]+\s[A-Z][a-z]+)/i

it won't work because now it'll match things such as "Guest post by small dog", which I don't want.

However, it needs to match with "GUEST POST BY Brian Williams".

like image 801
Henley Avatar asked Dec 12 '22 08:12

Henley


1 Answers

Use the case-insensitive modifier pattern:

(?i:)

In your case:

(?i:Guest post by )([A-Z][a-z]+\s[A-Z][a-z]+)

Working example: http://regex101.com/r/pW1gV9

Alternatively (thanks @robertodecumex!) you can use a modifier range, which is handy if you want to exclude the result from capture.

(?i)Guest post by(?-i) ([A-Z][a-z]+\s[A-Z][a-z]+)
like image 150
brandonscript Avatar answered Jan 08 '23 05:01

brandonscript