Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Use AND in Ruby Regex

Tags:

regex

ruby

I'm having problems with Ruby regex.

How do you do AND(&) regex in ruby?

ex:

cat and dog
cat
dog

I just want to match "cat and dog"
like image 559
gerky Avatar asked Jun 22 '11 09:06

gerky


People also ask

What does =~ mean in Ruby regex?

=~ is Ruby's basic pattern-matching operator. When one operand is a regular expression and the other is a string then the regular expression is used as a pattern to match against the string. (This operator is equivalently defined by Regexp and String so the order of String and Regexp do not matter.

Can you use regex in Ruby?

Two uses of ruby regex are Validation and Parsing. Ruby regex can be used to validate an email address and an IP address too. Ruby regex expressions are declared between two forward slashes. This will return the index of first occurrence of the word 'hi' if present, or else will return ' nil '.

How do you match a string in Ruby?

Ruby | Regexp match() functionRegexp#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. Return: regular expression with the string after matching it.

What is Rubular?

Rubular is a Ruby-based regular expression editor. It's a handy way to test regular expressions as you write them. To start, enter a regular expression and a test string.


2 Answers

You can do something like a AND using positive look aheads

(?=.*cat)(?=.*dog).*

See it here on Rubular Updated link!

This positive lookahead (?=.*cat) checks if there is "cat" somewhere within the string, then the same is done for "dog" using (?=.*dog). If those both assertions are true then the complete string is matched with the .* at the end.

The advantage is that it will also match

dog and cat

and not only

cat and dog

but it will also match

dogs and cats

if you want exact matches, then use this

(?=.*\bcat\b)(?=.*\bdog\b).*

\b is a word boundary, i.e. it matches between a word and a non word character.

See it here

like image 100
stema Avatar answered Sep 29 '22 11:09

stema


Your question is not very clear.

If you wish to match only those strings which contain both "cat" and "dog" (maybe as parts of a word), you could do:

/^.*(cat.*dog|dog.*cat).*$/

The above regex will match "concatenation dogma", but not "concatenation".

If you want to ensure that "cat" and "dog" appear as words by themselves, do:

/^.*(\bcat\b.*\bdog\b|\bdog\b.*\bcat\b).*$/

The above regex will match "cat and dog", but not "concatenation dogma" or "cat dogma".

Source: http://ruby-doc.org/docs/ProgrammingRuby/html/intro.html#S5

like image 24
Vicky Chijwani Avatar answered Sep 29 '22 12:09

Vicky Chijwani