首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >获取关键字、所有数字和句点的Regex

获取关键字、所有数字和句点的Regex
EN

Stack Overflow用户
提问于 2019-03-18 18:58:53
回答 3查看 81关注 0票数 0

我的输入文本如下:

放三个扩音器,但到了4楼,信号就弱了,这些都不像猪背一样。圣-99。5G DL 624.26上168.20 4g DL 2上.44

我很难编写一个与4G/5G/4g/5g的任何实例相匹配的正则表达式,并在这些代码的实例之后给出所有相应的测量值,这些代码都是带有小数的数字。

产出应是:

5G 624.26 168.20 4g 2 .44

有什么想法如何做到这一点吗?我试着用Python来做这个分析。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-03-18 19:22:22

我同意使用捕获组的答案,但是对于正则表达式本身有一种稍微不同的方法。确保使用gi (全局和不区分大小写的)选项来获得正确的结果。

代码语言:javascript
运行
复制
r"([45]G).*?([\d.]+).*?([\d.]+)"

我包括到我使用的在线正则表达式测试器和调试器的链接,因为它很好地解释了regex的各个元素,我还在下面生成的样例python代码中复制了它。

代码语言:javascript
运行
复制
import re

regex = r"([45]G).*?([\d.]+).*?([\d.]+)"

test_str = "Put in 3 extenders but by the 4th floor it is weak on signal these don't piggy back of each other. ST -99. 5G DL 624.26 UP 168.20 4g DL 2 Up .44"

matches = re.finditer(regex, test_str, re.IGNORECASE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
票数 1
EN

Stack Overflow用户

发布于 2019-03-18 19:11:35

我会把它分成不同的捕捉组,就像这样:

(?i)(?P<g1>5?4?G)\sDL\s(?P<g2>[^\s]*)\sUP\s(?P<g3>[^\s]*)

(?i)使整个正则表达式不敏感

(?P<g1>5?4?G)是第一个在4g、5g、4G或5G上匹配的组。

(?P<g2>[^\s]*)是第二组和第三组,它们匹配所有不是空格的内容。

然后,在Python中您可以这样做:

match = re.match('(?i)(?P<g1>5?4?G)\sDL\s(?P<g2>[^\s]*)\sUP\s(?P<g3>[^\s]*)', input)

并按如下方式访问每个组:

match.group('g1')等。

票数 1
EN

Stack Overflow用户

发布于 2019-03-18 19:15:19

代码语言:javascript
运行
复制
(5G|4G)\sDL\s(\d*[.]?\d*)\sUP\s(\d*[.]?\d*)

使用gi标志(全局的、不区分大小写的)应该可以工作。您可以修改数字匹配,因为我不确定它是否一定是小数。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55228336

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档