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"
=~ 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.
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 '.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With