JavaScript
x
2
1
words_to_remove = ['sstlgh8j', 'abchjk9j']
2
I need to remove the words in the sentance which starts with sst or abc
I have a sentence in this way:
JavaScript
1
3
1
1) error in node occurred in sstlgh8j at 10pm afterabchjk9j after 12pm
2
2) error in node occurredsstlgh8j at 10pm after abchjk9j after 12pm
3
I need to remove those words from the above two sentences. I tried with regex sub module but not working
JavaScript
1
2
1
re.sub('(?:s)sst[, ]*', '', my_string)
2
It is removing the word when there is a space only
JavaScript
1
4
1
Desired output:
2
1) error in node occurred in at 10pm after 12pm
3
2) error in node occurred at 10pm after 12pm
4
Advertisement
Answer
You can use
JavaScript
1
2
1
my_string = re.sub(r's*(?:abc|sst)w*', '', my_string)
2
See the regex demo. Details:
s*
– zero or more whitespace chars(?:abc|sst)
– eitherabc
orsst
w*
– zero or more word chars. Replace with[^Wd_]*
to match any Unicode letters or[a-zA-Z]*
to only match ASCII letters.
See a Python demo:
JavaScript
1
10
10
1
import re
2
texts = ['error in node occurred in sstlgh8j at 10pm afterabchjk9j after 12pm',
3
'error in node occurredsstlgh8j at 10pm after abchjk9j after 12pm']
4
rx = re.compile(r's*(?:abc|sst)w*')
5
for mystring in texts:
6
print(rx.sub('', mystring))
7
8
# => error in node occurred in at 10pm after after 12pm
9
# error in node occurred at 10pm after after 12pm
10