regex Python中的正则表达式排除字符串的最后3个单词?

hi3rlvi2  于 12个月前  发布在  Python
关注(0)|答案(4)|浏览(140)

我有一个字符串由至少4个空格分隔的单词组成。每一个字之间都可以有不止一个空格。
我需要用Python写一个函数(可能是一个正则表达式就足够了),它可以获取字符串的开头,不包括最后三个单词。
例如:

1) input_string = "word1    word2 word3      word4" => return 'word1'

2) input_string = "word1 word2 word3      word4 word5" => return 'word1 word2'
                                                          (with only a space between word1 and word2)

3) input_string = "word1    word2 word3      word4 word5" => return 'word1    word2'
                                                             (with 3 spaces between word1 and word2 as in the input_string)

我尝试使用以下代码:

def func(input_string):
    input_string = " ".join(input_string.split())
    l = len(input_string)
    start_string = input_string[0]
    if l > 4:
       i = 1
       start_string += ' '
       while i < l - 3:
           start_string += input_string[i]
           i += 1
           if i == l - 3:
               break
           else:
               start_string += ' '
    return start_string

我的代码适用于示例1和2,但不适用于示例3,其中word1word2之间存在3个空格。在这种情况下,我的函数返回"word1 word2",在word1word2之间只有一个空格。
谁能给予给我一个合适的正则表达式来达到我的目标?

u3r8eeie

u3r8eeie1#

也可以使用re.split()和slicing。

input_string = "word1    word2 word3      word4 word5"

print(re.split(r'\s+',input_string)[:3])
4jb9z9bj

4jb9z9bj2#

你可以使用regex。
你可以提取所有的单词,然后创建一个正则表达式,最后n个单词和任意数量的空格在它们之前,之间和之后,然后得到正则表达式结果之前的字符串

import re

def exclude_last_n_words(input_string, n=3):
    words = input_string.split()
    if len(words) <= n:
        return ''
    last_n_words = words[-n:]

    # Create a regex pattern for the last n words, allowing any number of spaces between them
    pattern = r'\s*'.join(re.escape(word) for word in last_n_words) + r'\s*$'

    # Find and remove the last n words
    match = re.search(pattern, input_string)
    if match:
        return input_string[:match.start()]
    else:
        return ''

input_string1 = "word1    word2 word3      word4"
input_string2 = "word1 word2 word3      word4 word5"
input_string3 = "word1    word2 word3      word4 word5"

print(exclude_last_n_words(input_string1))
print(exclude_last_n_words(input_string2))
print(exclude_last_n_words(input_string3))
ve7v8dk2

ve7v8dk23#

使用正则表达式匹配最后3个单词。

import re

def func(input_string):
    return re.sub(r'(?:\s+\w+){3}$', '', input_string)

print(func("word1    word2 word3      word4"))
print(func("word1 word2 word3      word4 word5"))
print(func("word1    word2 word3      word4 word5"))

\s+匹配空白字符序列,\w+匹配字母数字字符序列。{3}匹配这些组中的3个,$匹配字符串的结尾。

tvokkenx

tvokkenx4#

最可靠的方法是使用(\S+\s+\S+\s+\S+)$,如

import re
pattern = re.compile('(\S+\s+\S+\s+\S+)$')
print(pattern.search(words).groups())

相关问题