python - 新行前任意数量单词的正则表达式

标签 python regex

我解析了段落中的一些文本,我想将其拆分出来插入表中。

字符串看起来像:

[“有些文本不确定有多少数字或是否有任何特殊字符等。但我真的不在乎,我只想这个字符串中的所有文本\n 123一些更多的文本(50%和一些更多的文本)\n"]

我想要做的是拆分新行之前的第一个文本字符串,因为它是 - 无论它是什么。我开始尝试这个 [A-Za-z]*\s*[A-Za-z]*\s* 但很快意识到这不会将其剪切为该字符串中的文本是可变的。

然后我想获取第二个字符串中的数字,以下似乎是这样做的:

\d+

最后我想获取第二个字符串中的百分比,以下内容似乎适用于:

\d+(%)+

我计划在函数中使用它们,但正在努力编译第一部分的正则表达式?我还想知道后两部分的正则表达式是否最有效?

更新:希望这能让事情变得更清楚一点?

输入:

[' 第一个文本 block \n 123 我想要的统计数据(我想要的百分比的 25%)\n 第二个文本 block \n 456 我想要的第二个统计数据(我想要的第二个百分比的 50%)想要)\n 第三个文本 block \n 789 我想要的第三个统计数据 (75% 第三个百分比)\n 第四个文本 block \n 101 第四个统计数据 (100% 第四个百分比)\n]

期望的输出: enter image description here

最佳答案

第一行 2 行

您可以使用split来获取前两行:

import re

data = ["Some text unsure how many numbers or if any special charectors etc. But I don't really care I just want all the text in this string \n 123 some more text (50% and some more text) \n"]

first_line, second_line = data[0].split("\n")[:2]
print first_line
# Some text unsure how many numbers or if any special charectors etc. But I don't really care I just want all the text in this string

digit_match = re.search('\d+(?![\d%])', second_line)
if digit_match:
    print digit_match.group()
    # 123

percent_match = re.search('\d+%', second_line)
if percent_match:
    print percent_match.group()
    # 50%

请注意,如果百分比写在其他数字之前,则 \d+ 将匹配百分比(不带 %)。我添加了 negative-lookahead 以确保匹配的数字后面没有数字或 %

每对

如果你想继续解析行对:

data = [" The first chunk of text \n 123 the stats I want (25% the percentage I want) \n The Second chunk of text \n 456 the second stats I want (50% the second percentage I want) \n The third chunk of text \n 789 the third stats I want (75% the third percentage) \n The fourth chunk of text \n 101 The fourth stats (100% the fourth percentage) \n"]

import re

lines = data[0].strip().split("\n")

# TODO: Make sure there's an even number of lines
for i in range(0, len(lines), 2):
    first_line, second_line = lines[i:i + 2]

    print first_line

    digit_match = re.search('\d+(?![\d%])', second_line)
    if digit_match:
        print digit_match.group()

    percent_match = re.search('\d+%', second_line)
    if percent_match:
        print percent_match.group()

它输出:

The first chunk of text 
123
25%
 The Second chunk of text 
456
50%
 The third chunk of text 
789
75%
 The fourth chunk of text 
101
100%

关于python - 新行前任意数量单词的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42977632/

相关文章:

python - 如何在两个字典中找到匹配值的字典键?

python - 查找 map 上一条线下方的所有点

Java正则表达式删除Freemarker FTL标签

javascript - 如何在 JavaScript 中限制正则表达式搜索

Java:使用扫描仪分隔符作为标记

python - 包含编号和名称排序的列表

部分匹配的 Python 列表查找

python - view.showMaximized() 在 PyQt5 中不起作用

php - 如何在php中用preg_match_all分割这个字符串?

c# - 正则表达式替换特定控制字符,除了一些特殊情况 C#?