【问题标题】:Why is python regex not matching special characters?为什么 python 正则表达式不匹配特殊字符?
【发布时间】:2020-07-26 15:40:02
【问题描述】:

我想知道为什么以下不起作用。该表达式适用于 Regex101.com。但是,当我将 ’ 添加到电子表格中时,它会返回一个空数组,而不是至少匹配该字符串。

这是正则表达式:

[^A-z0-9\s,.][^-_+=]

这就是我正在寻找的:

’
Â

在这里试试(它对我有用): https://regex101.com/

代码如下:

import pandas as pd
import chardet
import csv 
import re

def get_file_encoding(file):
    rawdata = open(file, "rb").read()
    encoding = chardet.detect(rawdata)['encoding']
    return encoding

#Type in sanitized_ACAS_FULL_1
data = 'sanitized_ACAS_FULL_1.csv'
my_encoding = get_file_encoding(data)
#print(my_encoding)
my_encoding = 'UTF-8-SIG'
df = pd.read_csv(data, encoding=my_encoding, header=None, low_memory=False)

csv_rows = df.apply(lambda x: x.tolist(), axis=1)

sanitized_rows = []
for row in csv_rows:
    for item in row:
        index = row.index(item) 
        row[index] = str(item).strip()
        if 'nan' in str(item).strip():
            row[index] = "NA"

for row in csv_rows:
    for item in row:
        sanitized_rows.append(item)

match = []
for row in sanitized_rows:
    for entry in row:   
        if re.match(r'[^A-z0-9\s,.][^-_+=]', entry):
            match.append(entry)

print(match)

【问题讨论】:

  • A-z 不正确。应该是A-Za-z
  • 顺便说一句,这段代码看起来很麻烦而且不习惯。我建议您多熟悉一下 Pandas。

标签: python regex pandas csv


【解决方案1】:
(\GÂ)|(\Gâ)|(\G€)|(\G™)

这会分别获取您想要的字符。如果您希望将它们分组,您可以使用(\G’) 作为示例。记住\G 意味着比赛开始

希望对你有帮助。

【讨论】:

  • 你在回答什么问题?
  • @Toto 我是一个试图提供帮助的“新”用户,这是一个正则表达式问题,我用匹配的正则表达式字符串回答。
  • 很好,但这并不能回答问题。
猜你喜欢
  • 2021-11-03
  • 2015-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多