我有大约15000个需要解析的文件,其中可能包含列表中的一个或多个字符串/数字。我需要用匹配的字符串分隔文件。
给定一个字符串:3423423987,它可以独立地显示为“3423423987”,或显示为“342342987_1”或“342342987_1a”、“3423423987-1a”,但也可以是“2133423987”但是,我只想检测匹配序列,它不是另一个数字的一部分,只有当它有某种后缀时。
因此3423423987_1是可以接受的,但13423423987不是。
我在regex上遇到了麻烦,老实说我没怎么用过。
简单地说,如果我用一个可能的正反两方面的列表来模拟这个过程,那么对于给定的列表,我应该会得到7次点击我想把课文摘录到单词的结尾,以便以后能录下来。
这是我的代码:

def check_text_for_string(text_to_parse, string_to_find):
    import re
    matches = []
    pattern = r"%s_?[^0-9,a-z,A-Z]\W"%string_to_find
    return re.findall(pattern, text_to_parse)

if __name__ =="__main__":
    import re
    word_to_match = "3423423987"
    possible_word_list = [
                    "3423423987_1 the cake is a lie", #Match
                    "3423423987sdgg call me Ishmael",  #Not a match
                    "3423423987 please sir, can I have some more?", #Match
                    "3423423987", #Match
                    "3423423987 ", #Match
                    "3423423987\t", #Match
                    "adsgsdzgxdzg adsgsdag\t3423423987\t", #Match
                    "1233423423987", #Not a match
                    "A3423423987", #Not a match
                    "3423423987-1a\t", #Match
                    "3423423987.0", #Not a match
                    "342342398743635645" #Not a match
                    ]

    print("%d words in sample list."%len(possible_word_list))
    print("Only 7 should match.")
    matches = check_text_for_string("\n".join(possible_word_list), word_to_match)
    print("%d matched."%len(matches))
    print(matches)

但显然,这是错误的有人能帮我吗?

最佳答案

看起来你只是想确保这个数字不是作为浮点数的一部分来匹配的然后需要使用lookarounds、lookbehind和lookahead来禁止前后带有数字的点。

(?<!\d\.)(?:\b|_)3423423987(?:\b|_)(?!\.\d)

查看regex demo
要同时匹配“前缀”(或者,最好在这里称之为“后缀”),您需要在模式的末尾添加类似于\S*(零个或更多非空白)或(?:[_-]\w+)?(一个可选的-_序列,后跟1个+字字符)。
细节:
(?<!\d\.)-如果在当前位置之前有一个数字和一个点,则匹配失败
(?:\b|_)-单词边界或_(我们需要它,因为_是一个单词字符)
3423423987-搜索字符串
(?:\b|_)-同上
(?!\.\d)-如果点+数字正好在当前位置之后,则匹配失败。
所以,使用
pattern = r"(?<!\d\.)(?:\b|_)%s(?:\b|_)(?!\.\d)"%string_to_find

查看Python demo
如果可以有像Text with .3423423987 float value这样的浮动,则还需要在第一个之后添加另一个lookbehind(?<!\.)(?<!\d\.)(?<!\.)(?:\b|_)3423423987(?:\b|_)(?!\.\d)

09-16 05:46