Regex matches a specific word followed by another, along with a border id

I am doing regex in Python. I tried some combinations but didn't work. I am completely new to regular expressions. My problem is that I have a string like this.

string = ''' World is moving towards a particular point'''

      

I want it to be checked if the word "to the side" is present immediately after the word "move", and if so, I want to select the remainder of the string (after "to the side") until it ends with ".". or '-'. I am new to this. Please provide a good suggestion.

+3


source to share


4 answers


Something like

re.findall (r'(?<=moving towards )[^-.]*', string)
['a particular point']

      

  • (?<=moving towards )

    watch for approval. Asserts that the line is preceded bymoving towards

  • [^-.]*

    matches anything other than -

    or.




How does it fit

World is moving towards a particular point
                        |
     (?<=moving towards ) #checks if this position is presceded by moving towards 
                          #yes, hence proceeds with the rest of the regex pattern

World is moving towards a particular point
                        |
                      [^-.]

World is moving towards a particular point
                         |
                       [^-.] 

# and so on


World is moving towards a particular point
                                         |
                                       [^-.]

      

Demo Regex

+6


source


You need to use a negative appearance . but it works if you have .

or -

in your line if you cannot use @ nu11p01n73R answer.

>>> string = ''' World is moving towards a particular point.'''
>>> re.search(r'(?<=moving towards).*(?=\.|-)',string).group(0)
' a particular point'

      

(?<=moving towards).*

is a negative match behind (. *) after moving towards



and (?=\.|-)'

- negative appearance that matches all of the earlier ( \.|-

) which means .

or-

Regular expression visualization

Demo Debuggex

+1


source


import re
str = ''' World is moving towards a particular point'''
match = re.search('moving towards\s+([^.-]+)', str)
if match:
   var = match.group(1)

Output >>> a particular point     

      

regex debug link

https://www.regex101.com/r/wV7iC7/1

      

+1


source


To repeat the question, you want to check if the given string

word should "move" in the direction. Here's how to do it using the parse module :

import parse
string = "World is moving towards a particular point"

fmt = "moving {:w}"

result = parse.search(fmt, string)

assert result[0] == "towards"

      

Note that the format specification :w

causes the result to match letters and underscores.

0


source







All Articles