Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignoring case for part of regular expression

Is there an easy way to ignore case for part of a regular expression? I'm using Ruby 1.9.3 and Rails 3.2.8 (not sure if Rails helps at all, but thought I'd mention it).

For example, I want to check if a string is "Hello, my name is Bartholomew", but I only care that Bartholomew has proper capitalization. I could do:

/^[Hh][Ee][Ll][Ll][Oo], [Mm][Yy] [Nn][Aa][Mm][Ee] [Ii][Ss] Bartholomew$/

But that's such a pain. I know that I can ignore case for the whole string with /i at the end:

/^hello, my name is bartholomew$/i

But I can't split the string (the regular expression and the string itself are both entered by users).

like image 737
at. Avatar asked Jan 30 '26 07:01

at.


1 Answers

Here's one way to do it, by making the regex case-sensitive by default and marking the insensitive section:

> pattern = /(?i:hello, my name is) Bartholomew/
=> /(?i:hello, my name is) Bartholomew/
> pattern =~ 'Hello, my Name is Bartholomew'
=> 0
> pattern =~ 'Hello, my Name is bartholomew'
=> nil

The other way to do it is to make the regex case-insensitive by default, and marking the sensitive section:

> pattern = /hello, my name is (?-i:Bartholomew)/i
=> /hello, my name is (?-i:Bartholomew)/i
> pattern =~ 'Hello, my Name is Bartholomew'
=> 0
> pattern =~ 'Hello, my Name is bartholomew'
=> nil
like image 142
Chris Jester-Young Avatar answered Feb 01 '26 21:02

Chris Jester-Young



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!