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.
source to share
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
|
[^-.]
source to share
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-
source to share
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.
source to share