繁体   English   中英

一个正则表达式模式,匹配所有以 s 开头的单词开始并在以 s 开头的单词之前停止的单词

[英]A regex pattern that matches all words starting from a word with an s and stopping before a word that starts with an s

我正在尝试捕获字符串中的单词,以便第一个单词以 s 开头,如果下一个单词也以 s 开头,正则表达式将停止匹配。

例如。 我有字符串“Stack、Code 和 StackOverflow”。 我只想捕获“堆栈、代码和”,而不是在匹配中包含“StackOverflow”。

这就是我的想法:

  1. 以空格开头,后跟 s。
  2. 匹配所有内容,除非该组是一个空格和一个 s(我使用的是负前瞻)。

我试过的正则表达式:

(?<=\s)S[a-z -,]*(?!(\sS))

我不知道如何让它工作。

我认为这应该有效。 我从这个线程改编了正则表达式。 您也可以在这里进行测试。 我还包括了一个非正则表达式的解决方案。 我基本上跟踪第一次出现的以“s”开头的单词和下一个以“s”开头的单词,并获取该范围内的单词。

import re

teststring = " Stack, Code and StackOverflow"
extractText = re.search(r"(\s)[sS][^*\s]*[^sS]*", teststring)

print(extractText[0])

#non-regex solution
listwords = teststring.split(' ')

# non regex solution
start = 0
end = 0
for i,word in enumerate(listwords):
    if word.startswith('s') or word.startswith('S'):
        if start == 0:
            start = i
        else:
            end = i
            break

newstring = " " + " ".join([word for word in listwords[start:end]])
print(newstring)

Output

 Stack, Code and
 Stack, Code and

您可以使用例如捕获组:

(S(?<!\S.).*?)\s*S(?<!\S.)

解释

  • (捕获组 1
    • S(?<.\S.)匹配S并断言S的左侧没有空白边界
    • .*? 匹配任意字符,尽可能少
  • )关闭组
  • \s*匹配可选的空白字符
  • S(?<.\S.)匹配S并断言S的左侧没有空白边界

请参阅正则表达式演示Python 演示

示例代码:

import re

pattern = r"(S(?<!\S.).*?)\s*S(?<!\S.)"
s = "Stack, Code and StackOverflow"
m = re.search(pattern, s)
if m:
    print(m.group(1))

Output

Stack, Code and

另一种选择使用环视将S断言到右侧而不使用它以允许多个匹配项相互匹配:

 S(?<!\S.).*?(?=\s*S(?<!\S.))

正则表达式演示

import re

pattern = r"S(?<!\S.).*?(?=\s*S(?<!\S.))"
s = "Stack, Code and StackOverflow test Stack"
print(re.findall(pattern, s))

Output

['Stack, Code and', 'StackOverflow test']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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