python - 可选的结束符号和使用正则表达式捕获的几个单词

标签 python regex string parsing syntax

是否可以编写一个正则表达式公式,可以捕获多个单词字符加上以 # 开头的 -,但如果 # 位于以空格分隔的几个单词的末尾,然后捕获开头和结尾之间的整个文本 #?

我相信我的代码比我的描述更容易理解:

import re

s = """
this is a dummy #text with some #dummy_short-tags
and a #full length long tag# that has closing symbol.
"""

print re.findall(r'#([\w-]+)', s)
# --> ['text', 'dummy_short-tags', 'full']
print re.findall(r'#(.+)?(?<!\s)#', s)
# --> ['full length long tag']

我可以将上面的两个正则表达式合并为一个吗?因此,我可以避免同时捕获“完整”和“全长长标签”,而且我的目标是将捕获的文本视为一种数据类型。

提前致谢!

最佳答案

使用交替:

re.findall('#([\w\s]+\w(?=#)|[\w-]+)', s)

输出:

['text', 'dummy_short-tags', 'full length long tag']

关于python - 可选的结束符号和使用正则表达式捕获的几个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17226119/

相关文章:

python - 我不明白 format() 和 ... (python) 之间有什么区别

Python:行长可以变化的字符串格式

java - 在字节数组中查找特定字符?

Python时间表 "Time is freezing"

regex.replace() 中的 C# 多个模式

python - 字符串到 int 的转换错误?

php - 替换单词并保持找到的字符串区分大小写

c# - 如何处理 XML 属性值中未转义的引号字符?

python - 最大小费计算器 - 天真的解决方案

python - Distutils:构建共享一个方法的多个Python扩展模块(用Swig编写)