匹配特定单词后的所有内容

匹配特定单词后的所有内容

本文介绍了正则表达式:匹配特定单词后的所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Python 并希望匹配 test 之后的所有单词,直到遇到句点(句号)或空格.

text = "test : match this."

目前,我正在使用:

导入重新re.match('(?<=test :).*',text)

上面的代码不匹配任何东西.我需要 match this 作为我的输出.

解决方案

如果您只是从字符串中获取子集,我不明白您为什么要使用正则表达式.

这也是一样的:

if line.startswith('test:'):打印(行 [5:line.find('.')])

示例:

>>>line = "测试:匹配这个.">>>打印(行 [5:line.find('.')])匹配这个

Regex 速度慢,设计笨拙,调试困难.肯定有使用它的场合,但如果你只是想提取 test:. 之间的文本,那么我认为不是这些场合之一.

参见:https://softwareengineering.stackexchange.com/questions/113237/when-you-should-not-use-regular-expressions

为了获得更大的灵活性(例如,如果您要遍历要在字符串开头查找的字符串列表,然后将其索引出来),请将索引中的 5('test:' 的长度)替换为 len(str_you_looked_for).

I am using Python and would like to match all the words after test till a period (full-stop) or space is encountered.

text = "test : match this."

At the moment, I am using :

import re
re.match('(?<=test :).*',text)

The above code doesn't match anything. I need match this as my output.

解决方案

I don't see why you want to use regex if you're just getting a subset from a string.

This works the same way:

if line.startswith('test:'):
    print(line[5:line.find('.')])

example:

>>> line = "test: match this."
>>> print(line[5:line.find('.')])
 match this

Regex is slow, it is awkward to design, and difficult to debug. There are definitely occassions to use it, but if you just want to extract the text between test: and ., then I don't think is one of those occasions.

See: https://softwareengineering.stackexchange.com/questions/113237/when-you-should-not-use-regular-expressions

For more flexibility (for example if you are looping through a list of strings you want to find at the beginning of a string and then index out) replace 5 (the length of 'test:') in the index with len(str_you_looked_for).

这篇关于正则表达式:匹配特定单词后的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 18:52