开发者

How to Use AND in Ruby Regex

I'm having problems with Ruby regex.

H开发者_JS百科ow do you do AND(&) regex in ruby?

ex:

cat and dog
cat
dog

I just want to match "cat and dog"


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


and is the default action in a regexp, i.e. first match this then followed by that and so on.

to match cat AND dog, use something like

cat.*dog

which means, match "cat" followed by anything AND then followed by "dog". But then again I might have misunderstood your question...


It depends of what you want.

You can use wild card

cat.+dog

Or

cat.+dog|dog.+cat

Or

cat +and +dog


There is no and operator in Regexps, simply because it doesn't make sense. It will never match: how can a String both be 'cat' and 'dog' at the same time?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜