正则表达式提取单词与实数:如何去除数字末尾多余点号?
提取字符串中的单词和实数并清理多余符号
下面提供两种实用的解决方案,完美处理你遇到的数字末尾点号问题:
方法一:直接匹配目标内容拼接
这种思路更高效,直接找出所有符合要求的内容再拼接,避免多次替换的麻烦。
import re def extract_valid_content(input_str): # 匹配带负号的实数(整数/小数)和字母数字组合的单词 pattern = r'-?(?:\d+\.\d+|\d+)|[a-zA-Z0-9]+' valid_items = re.findall(pattern, input_str) return ' '.join(valid_items) # 测试你的示例输入 test_input = "word1, word2.word3, 1.4056 -1.2456 40,50 -60$30 60.50. 70.40." print(extract_valid_content(test_input)) # 输出:word1 word2 word3 1.4056 -1.2456 40 50 -60 30 60.50 70.40
正则说明
-?(?:\d+\.\d+|\d+):精准匹配带可选负号的实数,不管是小数(如1.4056)还是整数(如40)都能覆盖[a-zA-Z0-9]+:匹配包含字母和数字的单词(比如word1、word2)
方法二:分阶段替换优化
如果你想基于你原来的re.sub思路调整,可以分三步处理:
import re def clean_target_string(input_str): # 1. 先去掉数字末尾的孤立点(比如60.50.里最后那个多余的点) step1 = re.sub(r'(?<=\d)\.(?!\d)', '', input_str) # 2. 把所有无关符号替换成空格 step2 = re.sub(r'[^a-zA-Z0-9.-]+', ' ', step1) # 3. 合并连续空格,清理首尾空格 step3 = re.sub(r'\s+', ' ', step2).strip() return step3 # 测试示例 test_input = "word1, word2.word3, 1.4056 -1.2456 40,50 -60$30 60.50. 70.40." print(clean_target_string(test_input)) # 输出:word1 word2 word3 1.4056 -1.2456 40 50 -60 30 60.50 70.40
正则说明
(?<=\d)\.(?!\d):用断言精准定位“数字后面、非数字前面”的点,只删这种多余的点[^a-zA-Z0-9.-]+:把所有不属于字母、数字、负号、点的字符换成空格\s+:把连续的多个空格合并成一个,同时去掉首尾的空格
内容的提问来源于stack exchange,提问作者supermiedos
相关产品推荐
相关产品推荐

