Python Re,如何捕获12&quot' / 14“”

发布于 2025-01-30 13:19:32 字数 545 浏览 3 评论 0原文

我需要捕获这样的模式:

12"" / 14""

"Factory SP1 150 12"" / 14"""

数字中更改(总是2位数字),其余的不会。
请注意,字符串末端的双引号是字符串的一部分,而不是封装器。

另请注意,我正在与Pandas合作,并使用.str.Extract(staters)

我的代码:

df = pd.read_csv(r'filename.csv', delimiter = ';', usecols = ["OLD_COLUMN", "OTHER_COLUMNS"], encoding='utf-8', error_bad_lines=False)

pattern = r'(\d{2}""\s*/\s*\d{2}"")'

df["NEW_COLUMN"] = df["OLD_COLUMN"].str.extract(pattern)

我更改了组,试图逃脱每个角色。我找不到方法。

I need to capture patterns like this one:

12"" / 14""

in

"Factory SP1 150 12"" / 14"""

The numbers change (always 2 digits), the rest doesn't.
Note that the double quotes at the ends of the string are part of the string and not enclosers.

Also note that I'm working with pandas and using .str.extract(pattern).

My code:

df = pd.read_csv(r'filename.csv', delimiter = ';', usecols = ["OLD_COLUMN", "OTHER_COLUMNS"], encoding='utf-8', error_bad_lines=False)

pattern = r'(\d{2}""\s*/\s*\d{2}"")'

df["NEW_COLUMN"] = df["OLD_COLUMN"].str.extract(pattern)

I changed groups, tried to escape every character. I can't find a way.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

凑诗 2025-02-06 13:19:33
pattern = '([0-9]+""\s*/\s*[0-9]+"")'

是一条正则态度,将与其他表达式匹配,例如1351“/1”“”。问题是您使用r或原始字符串。它在模式中导致您的\被解释为字面意义\。因此,您的原始图案只能匹配12 \“ \” / 14 \“ \” < / code>之类的字符串

pattern = '([0-9]+""\s*/\s*[0-9]+"")'

Is a regex that will match that along with other expressions like 1351""/1"". The issue is your use of the r or raw string. It causes your \ in the pattern to be interpreted as literally \. So your original pattern would only match strings like 12\"\" / 14\"\"

南风起 2025-02-06 13:19:32

您可以使用r'\ d {2}“” \ s*/\ s*\ d {2}“”' as Regex:

s = '"Factory SP1 150 12"" / 14"""'
re.findall(r'\d{2}""\s*/\s*\d{2}""', s)

uption:输出:

['12"" / 14""']

请小心您的字符串:sp1 150 12“” / 14“”“ < / code>等效于:“工厂SP1 150 12” +“ / 14” +“” < / code> so '工厂SP1 SP1 150 12/14 '

You can use r'\d{2}""\s*/\s*\d{2}""' as regex:

s = '"Factory SP1 150 12"" / 14"""'
re.findall(r'\d{2}""\s*/\s*\d{2}""', s)

output:

['12"" / 14""']

Be careful with your strings: "Factory SP1 150 12"" / 14""" is equivalent to: "Factory SP1 150 12" + " / 14" + "" so 'Factory SP1 150 12 / 14'

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文