Python 从字符串中获取单词
如何从这样的字符串中获取word示例:Python 从字符串中获取单词,python,regex,Python,Regex,如何从这样的字符串中获取word示例: str = "http://test-example:123/wd/hub" 我写过这样的东西 print(str[10:str.rfind(':')]) 但如果字符串是 "http://tests-example:123/wd/hub" 您可以使用以下非正则表达式,因为您知道示例是一个7个字母的单词: s.split('-')[1][:7] 对于任意单词,将更改为: s.split('-')[1].split(':')[0] 您可以使用此正则
str = "http://test-example:123/wd/hub"
我写过这样的东西
print(str[10:str.rfind(':')])
但如果字符串是
"http://tests-example:123/wd/hub"
您可以使用以下非正则表达式,因为您知道示例是一个7个字母的单词:
s.split('-')[1][:7]
对于任意单词,将更改为:
s.split('-')[1].split(':')[0]
您可以使用此正则表达式捕获前面有
-
和后面有:
的值
非正则表达式获得相同结果的方法是使用这两个拆分
str = "http://test-example:123/wd/hub"
print(str.split(':')[1].split('-')[1])
印刷品
example
在
-
上拆分,然后在上拆分:
s = "http://test-example:123/wd/hub"
print(s.split('-')[1].split(':')[0])
#example
使用稀土
import re
text = "http://test-example:123/wd/hub"
m = re.search('(?<=-).+(?=:)', text)
if m:
print(m.group())
重新导入
文本=”http://test-example:123/wd/hub"
m=重新搜索(')(?多种方法
使用拆分:
example_str=str.split('-')[-1]。split(':')[0]
这是易碎的,如果字符串中有更多连字符或冒号,则可能会断裂
使用正则表达式:
重新导入
pattern=re.compile(r'-(.*):')
示例_str=pattern.search(str.group)(1)
这仍然需要特定的格式,但更容易适应(如果您知道如何编写正则表达式)。Python字符串具有内置函数:
将返回:
12
-1
它是找到的子字符串的索引。如果它等于-1
,则在字符串中找不到该子字符串。您也可以在关键字中使用:
中的“示例”http://test-example:123/wd/hub“
True
我不确定您为什么要从字符串中获取特定的单词。我猜您想看看这个单词在给定的字符串中是否可用
如果是这种情况,可以使用下面的代码
import re
str1 = "http://tests-example:123/wd/hub"
matched = re.findall('example',str1)
您可以将(?与re?Like re.search(')(?是的。让我在答案中添加和说明。
import re
text = "http://test-example:123/wd/hub"
m = re.search('(?<=-).+(?=:)', text)
if m:
print(m.group())
a="http://test-example:123/wd/hub"
b="http://test-exaaaample:123/wd/hub"
print(a.find('example'))
print(b.find('example'))
12
-1
import re
str1 = "http://tests-example:123/wd/hub"
matched = re.findall('example',str1)