Skip to content Skip to sidebar Skip to footer

Regex Replace Mixed Number+strings

I want to remove all words containing numbers, examples: LW23 London W98 String From the string above the only thing i want to remain is 'London String'. Can this be done with reg

Solution 1:

Yes, you can:

result=re.sub(r"""(?x)# verbose regex\b# Start of word(?=# Look ahead to ensure that this word contains...\w*# (after any number of alphanumeric characters)\d# ...at least one digit.)# End of lookahead\w+# Match the alphanumeric word\s*# Match any following whitespace""", "",subject)

Solution 2:

You can try a preg_replace with this pattern:

/(\w*\d+\w*)/

Something like $esc_string = preg_replace('/(\w*\d+\w*)/', '', $old_string);

Solution 3:

Depends on what a 'word' is I guess, but if we're talking whitespace as separators and if it doesn't have to be a regex:

>>> ' '.join(filter(str.isalpha, a.split()))
'London String'

Solution 4:

I'm not 100% sure and this is just a suggestion for a possible solution, I'm not a python master but I'd probably have a better idea of what todo if I saw the full code.

My suggestion would be to add the sections of the string to a list, pop each word out and use and if function to check for numbers and remove them if they contain number and add them to a new list if they do not, you could then re-order the list to have the words in the appropriate order.

Sorry if this doesn't help, I just know that if I encountered the problem, this sort of solution is where I would start.

Solution 5:

You could do this with a regex plus comprehension:

clean = [w for w in test.split(' ') if not re.search("\d", w)]

or

words = test.split(' ')
regex = re.compile("\d")
clean = [w for w in words if not regex.search(w) ]

Input:

"LW23 London W98 String X5Y 99AP Okay"

Output:

['London', 'String', 'Okay']

Post a Comment for "Regex Replace Mixed Number+strings"