首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >替换重复字符正则表达式

替换重复字符正则表达式
EN

Stack Overflow用户
提问于 2013-10-27 04:22:36
回答 4查看 2K关注 0票数 2

我是正则表达式的新手。

我想替换字符串中的重复字符。下面是一些例子

代码语言:javascript
运行
复制
$str1 = "aaa bbb cc dddd";  // output : a b c d

$str2 = "Google is the best";  // output : Google is the best

我在stackoverflow上发现了很多与这个问题相关的问题。但它不能满足我的要求。

我试过这个(\w)\1,但这不是我的解决方案

有什么想法吗?提前感谢

编辑:

更多示例

代码语言:javascript
运行
复制
 $str1 = "this is tesaaat. are you ook?";  // output : this is tesaaat. are you ook?

 $str2 = "Good morning mmmm yyyy friendssss ";  // output : Good morning m y friends

 $str3 = "Hello friendd okk";  // output : Hello friend okk 

简而言之,我想替换重复的字符,后面只跟空格。

EN

回答 4

Stack Overflow用户

发布于 2013-10-27 04:31:47

您可以使用以下正则表达式:\b(\w)\1+\b

解释:

至少一次相同的单词分隔符和单个字符重复(至少一次相同的(\b)

  • A a

编辑:如果有更多的细节,我会说你可以去掉第一个\b。因此,它变成了:(\w)\1+\b

票数 4
EN

Stack Overflow用户

发布于 2013-10-27 15:48:11

下面的正则表达式适用于任何语言中带有u-unicode标志的所有字母:

代码语言:javascript
运行
复制
/([\p{L}\W])\1+(?= )/u

解释:

代码语言:javascript
运行
复制
(                 # beginning of 1st capturing group
    [             # beginning of characters class
        \p{L}     # any letter from any language
        \W        # any non-word character
    ]             # end of character class
)                 # end of 1st capturing group
\1                # back reference to our 1st capturing group for repetition
+                 # one or more character repetition
(?= )             # using positive lookahead to be sure it's followed by a space

使用preg_replace来完成以下工作:

代码语言:javascript
运行
复制
$string = preg_replace("/([\p{L}\W])\1+(?= )/u", "$1", $string);

示例的输出:

代码语言:javascript
运行
复制
"aaa bbb cc dddd "  =>  "a b c d "
"Google is the best"  =>  "Google is the best"
"this is tesaaat. are you ook?"  =>  "this is tesaaat. are you ook?"
"Good morning mmmm yyyy friendssss "  =>  "Good morning m y friends "
"Hello friendd okk"  =>  "Hello friend okk"
票数 3
EN

Stack Overflow用户

发布于 2013-10-27 04:41:04

代码语言:javascript
运行
复制
$text = "aaa bbb cc dddd";
$replacedText = preg_replace('{(\w)\1+}','$1',$text);

如果您也不想要重复的空格,请尝试以下操作:

代码语言:javascript
运行
复制
$replacedText = preg_replace('{(.)\1+}','$1',$text);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19611499

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档