I'm trying to find if the last word of the string is followed by a space or a special char, and if yes return the string without this space/special char
For example :
"do you love dogs ?" ==> return "do you love dogs"
"i love my dog " (space after dog) ==> return "i love my dog"
"do you love dogs?" ==> return "do you love dogs"
So far I tried :
re.search(re.compile(r"^[^\,\(\[\.\!\?]*"), mystring)
It works in the last example but not in the first two (it keeps the space of the second example) and I don't know how to deal with it.
EDIT : the special chars are : '.', '!', '?', '(', '[',',' at first then every other non numeric/alphabetical except those
If you want to remove the space and the special char from the end of those 3 sentences, using regex, this is one way you can do it:
import re
print re.findall(r'\w+\s\w+\s\w+\s\w+', "i love my dog ")
print re.findall(r'\w+\s\w+\s\w+\s\w+', "do you love dogs ?")
print re.findall(r'\w+\s\w+\s\w+\s\w+', "do you love dogs?")
Output:
['i love my dog']
['do you love dogs']
['do you love dogs']
Updated: This will check for the existence of a sentence followed by special characters. It returns false if there are no special characters, and your original sentence is in capture group 1.
r"(.*[\w])([^\w]+)"
Alternatively (without a second capture group):
Regex101 Example - no second capture group
r"(.*[\w])(?:[^\w]+)"
That's what you're looking for right?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.