从字符串中获取单词

2024-04-18 16:14:22 发布

您现在位置:Python中文网/ 问答频道 /正文

如何从这样的字符串中获取word示例

str = "http://test-example:123/wd/hub"

我写了这样的东西

print(str[10:str.rfind(':')])

但如果字符串像

"http://tests-example:123/wd/hub" 

Tags: 字符串testhttp示例exampletestswordhub
3条回答

您可以使用以下非正则表达式,因为您知道示例是一个7个字母的单词:

s.split('-')[1][:7]

对于任意单词,将更改为:

s.split('-')[1].split(':')[0]

多种方式

使用拆分:

example_str = str.split('-')[-1].split(':')[0]

这是脆弱的,如果字符串中有更多的连字符或冒号,可能会断开。你知道吗

使用正则表达式:

import re
pattern = re.compile(r'-(.*):')
example_str = pattern.search(str).group(1)

这仍然需要一种特定的格式,但更容易适应(如果您知道如何编写regex的话)。你知道吗

您可以使用这个正则表达式捕获前面是-的值,后面是使用lookarounds:

(?<=-).+(?=:)

Regex Demo

Python代码

import re

str = "http://test-example:123/wd/hub"

print(re.search(r'(?<=-).+(?=:)', str).group())

输出

example

非正则表达式实现相同的方法是使用这两个拆分

str = "http://test-example:123/wd/hub"

print(str.split(':')[1].split('-')[1])

指纹

example

相关问题 更多 >