Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is '?-mix' in a Ruby Regular Expression

Tags:

regex

ruby

Just trying to debug a regular expression in ruby. When I print the contents of a regular expression, it shows ?-mix at the beginning of the regular expression even though those characters were not part of the expression. Please see the following IRB output to see this illustrated

irb(main):028:0* EXPR = /^a$/ => /^a$/ irb(main):029:0> EXPR => /^a$/ irb(main):030:0> puts EXPR (?-mix:^a$) => nil 

As you can see, when you use puts to print out the contents of a regular expression, there is ?-mix at the beginning. Should I be concerned by this? Where is it coming from?

like image 601
Plastikfan Avatar asked Feb 20 '15 14:02

Plastikfan


People also ask

What does =~ mean in Ruby regex?

=~ is Ruby's pattern-matching operator. It matches a regular expression on the left to a string on the right. If a match is found, the index of first match in string is returned. If the string cannot be found, nil will be returned.

What kind of regex does Ruby use?

A regular expression is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings. Ruby regular expressions i.e. Ruby regex for short, helps us to find particular patterns inside a string. Two uses of ruby regex are Validation and Parsing.

What does match do in Ruby?

Ruby | Regexp match() function Regexp#match() : force_encoding?() is a Regexp class method which matches the regular expression with the string and specifies the position in the string to begin the search.


1 Answers

mix is not the English word mix, it's options of Regexp.

See Regexp#to_s:

Returns a string containing the regular expression and its options (using the (?opts:source) notation.

In your example, m is for multiline mode, i is for case insensitive, and x is for extended mode. Options before the dash are on, those after are off (default). The question's example, ?-mix, has all options off.

You can turn them on like:

puts /^a$/mix # =>(?mix:^a$) 
like image 109
Yu Hao Avatar answered Oct 04 '22 15:10

Yu Hao