gpt4 book ai didi

regex - 如何通过正则表达式识别 "text"单词?

转载 作者:行者123 更新时间:2023-12-02 01:44:26 26 4
gpt4 key购买 nike

什么 perl 正则表达式匹配以下文件名中的“单词”?

我有一系列文件名,其中有些单词出现不止一次:

john_smith_on_alaska_trip_john_smith_0001.jpg

他妻子的名字是 Olga,在 o 上有一个变音符号,还有一些其他名字带有变音符号;全部小写,在我的情况下,但不仅仅是英语 a-z。由于其他原因,.jpg 已被暂时删除,在本次讨论中可能会被忽略。

我想删除重复的名称/单词。类似这样的东西在 emacs 中运行良好:

s/(\b\w{3,}\b)(.*)(\b\1\b)/\1\2/

运行一次,上面变成:john_smith_on_alaska_trip__smith_0001.jpg

同样:john_smith_on_alaska_trip___0001.jpg

在 Perl 中,这不起作用,因为 \w 包含 _ 作为单词字符。更糟糕的是 - anchor \b 不是那些字符,因此不会在 _ 上分开。

我目前的解决方案是将所有 _ 替换为 ,执行操作,然后还原。但是,这似乎是一个基本要求,我觉得我一定遗漏了一些东西。

谢谢。

最佳答案

使用 Character Class \p{Alpha}Lookbehind and Lookahead assertions代替单词边界以确保每个单词都是一个完整的单词而不是子字符串:

use strict;
use warnings;

my $file = "john_smith_on_alaska_trip_john_smith_0001_johnsmith.jpg";

1 while $file =~ s{
(?<!\p{Alpha}) ( \p{Alpha}++ ) # Word surrounded by non-word chars
.* \K # Keep everything before this point
(?<!\p{Alpha}) \1 (?!\p{Alpha}) # Strip duplicate word
}{}x;

print "$file\n";

输出:

john_smith_on_alaska_trip___0001_johnsmith.jpg

Live Demo

关于regex - 如何通过正则表达式识别 "text"单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26558671/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com