简体   繁体   中英

Regex to remove characters after multiple white spaces

Hi all I've got and input strings:

list_of_strings = ["apple", "orange ca", "pear  sa", "banana    sth"]

And I want to remove everything after multiple white spaces (more than 1), so end result is:

final_list_of_strings = ["apple", "orange ca", "pear", "banana"]

I've tried regex:

import re

regex_expression = r"(.*\s?)(\s{2,}.*)"

for name in list_of_strings:
    regex_matching_groups = re.findall(regex_expression, name)
    if regex_matching_groups:
    name = regex_matching_groups[0][0]
    

but fails on multiple spaces ... Thank you for help!

You can use re.sub in a list comprehension:

import re
list_of_strings = ["apple", "orange ca", "pear  sa", "banana    sth"]
list_of_strings = [re.sub(r'\s{2}.*', '', x, flags=re.S) for x in list_of_strings]
print(list_of_strings)
# -> ['apple', 'orange ca', 'pear', 'banana']

See the Python demo .

The \\s{2}.* regex matches two whitespace chars and then the rest of the string (even if there are line break chars due to re.S flag).

using a regular expression find the first word and optionally a second word with only one space between

list_of_strings = ["apple", "orange ca", "pear  sa", "banana    sth"]

my_list=[]
def find_phrase(list_of_strings):
    for string in list_of_strings:
        matches=re.findall(r"(\w+)( \w+)*", string)
        if len(matches)>0:
            my_list.append("".join([matches[0][0],matches[0][1]]))
    return my_list
        
 print(find_phrase(list_of_strings))

output:

['apple', 'orange ca', 'pear', 'banana']

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM