0
0
0xC0CAC01A2018-08-11 11:17:39
Regular Expressions
0xC0CAC01A, 2018-08-11 11:17:39

How to write it as a regular expression?

Let's say I want to create a regular expression that passes any string containing "white" or "gray" and "hippo" or "hippo", including plurals but not containing the word "hungry" or "angry", case insensitive .
Those. informally, I want something like: ("white" OR "grey") AND ("behemoth[s]" OR "hippo[s]") -"wild" -"evil"
The following must pass:
"some white hippos look great"
"this hippo is painted gray"
"white and gray hippos"
Should not pass:
"I like white" (no mention of hippos)
"
And by the way, is there a library (preferably in python) that would convert readable terms like:
("white" OR "gray") AND ("behemoth[s]" OR "hippo[s]") -"wild " -"evil",
into regular expressions?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
dodo512, 2018-08-11
@dodo512

^(?: (word1) | (word2) | ... )+
After passing through the line, we check which of the preserving groups participated in the match.
(?(id/name)yes-pattern|no-pattern) https://docs.python.org/3/library/re.html
You will also need atomic grouping (?>...), which is not supported in Python, but can be simulated with positive lookahead (?=...)
https://regex101.com/r/dbjy2E/1

pattern = r"""
(?xm)  
^
(?=
  (
    (?: \b (?P<a> белый | серый | красные ) \b
      | \b (?P<b> бегемот[ы]? |гиппопотам[ы]? ) \b
      | \b (?P<c> дикий | злой ) \b
      | \w+
      | [^\w\n]+
    )+
  )
)

(?(a)|(?!))
(?(b)|(?!))
(?(c)(?!)|)
"""

D
Dimonchik, 2018-08-11
@dimonchik2013

if in front of the boys, then replace regexp with bagwords, the word is also pontoon, and the solution will be

S
silent-tempest, 2018-08-12
@silent-tempest

works on js (only about pink ones it doesn't match)

/^(?=.*(?:белы[йе]|серы[йе]))(?=.*(?:бегемоты?|гиппопотамы?))(?!.*(?:дики[йе]|зл(?:ой|ые))).*$/

N
Nick Sdk, 2018-08-12
@lidacriss

/(?=.*?(белы[йе]|серы[йе]))(?=.*?(бегемот[ы]?|гиппопотам[ы]?))(?!.*?(дикий))(?!.*?(злой))/i

even like this
https://jsfiddle.net/kwz7duqm/
did not notice at first, but silent-tempest got a very similar regular expression

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question