Regex: matching parts of a string when a string contains part of a regular expression pattern

I want to reduce the number of patterns that I need to write using a regular expression that matches any or all of the patterns when it appears in a string.

Is this possible with Regex?

E.g. Pattern is: "the cat sat on the mat"

I would like pattern to match on following strings:
"the"
"the cat"
"the cat sat"
...
"the cat sat on the mat"

But it should not coincide with the next line, because although some words correspond to each other, they are separated by an inappropriate word: "the dog was sitting"

+1
source share
4 answers

It:

the( cat( sat( on( the( mat)?)?)?)?)?

answer your question. Delete "optional parens groups (...)?" for parts that are not optional, add additional groups for things that should match.

the                       // complete match
the cat                   // complete match
the cat sat               // complete match
the cat sat on            // complete match
the cat sat on the        // complete match
the cat sat on the mat    // complete match
the dog sat on the mat    // two partial matches ("the")

, , , , , "" :

^the( cat( sat( on( the( mat)?)?)?)?)?

: -, , , :

the( cat( sat( on( the( mat)?)?)?)?)?$

VonC. !

, , - , .

, :

the( cat( sat( on( the( mat)?)?)?)?)

: " ", .

+7

:

(?ms)the(?=(\s+cat)|[\r\n]+)(:?\s+cat(?=(\s+sat)|[\r\n]+))?(:?\s+sat(?=(\s+on)|[\r\n]+))?(:?\s+on(?=(\s+the)|[\r\n]+))?(:?\s+the(?=(\s+mat)|[\r\n]+))?(:?\s+mat)?[\r\n]+

:

  • "the", "cat"
  • "cat" (), "sat"
  • , ,
  • ( , " ..." )




( )
( )


, Tomalak ( , "$" ).
.

+2

, , . , Regex .

+1

, -..

, ... .

,

string = " " pattern = " "

.

, -)

0

Source: https://habr.com/ru/post/1729821/


All Articles