我的输入文本如下:
放三个扩音器,但到了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来做这个分析。
发布于 2019-03-18 19:22:22
我同意使用捕获组的答案,但是对于正则表达式本身有一种稍微不同的方法。确保使用gi (全局和不区分大小写的)选项来获得正确的结果。
r"([45]G).*?([\d.]+).*?([\d.]+)"
我包括到我使用的在线正则表达式测试器和调试器的链接,因为它很好地解释了regex的各个元素,我还在下面生成的样例python代码中复制了它。
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.
发布于 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')
等。
发布于 2019-03-18 19:15:19
(5G|4G)\sDL\s(\d*[.]?\d*)\sUP\s(\d*[.]?\d*)
使用gi标志(全局的、不区分大小写的)应该可以工作。您可以修改数字匹配,因为我不确定它是否一定是小数。
https://stackoverflow.com/questions/55228336
复制相似问题