匹配连续重复字符

2024-06-24 18:21:57 420
匹配连续重复字符的正则表达式与解析,包含Python、

正则表达式

(.)\1+

解释

  • (.):匹配任意一个字符,并将其捕获到一个组中。
  • \1:引用前面捕获的组,即重复匹配相同的字符。
  • +:匹配前面字符(\1)的一个或多个重复。

用法

Python

import re

pattern = r'(.)\1+'
test_strings = ["aaabbb", "abcd", "aabbcc", "helloo", "no_repeat"]

for test_string in test_strings:
    matches = re.findall(pattern, test_string)
    if matches:
        print(f"'{test_string}': 匹配到重复字符 {matches}")
    else:
        print(f"'{test_string}': 没有匹配到重复字符")

JavaScript

const pattern = /(.)\1+/;
const testStrings = ["aaabbb", "abcd", "aabbcc", "helloo", "no_repeat"];

testStrings.forEach(testString => {
    const matches = testString.match(pattern);
    if (matches) {
        console.log(`'${testString}': 匹配到重复字符 ${matches[0]}`);
    } else {
        console.log(`'${testString}': 没有匹配到重复字符`);
    }
});

Java

import java.util.regex.*;

public class RegexTest {
    public static void main(String[] args) {
        String pattern = "(.)\\1+";
        String[] testStrings = {"aaabbb", "abcd", "aabbcc", "helloo", "no_repeat"};
        
        for (String testString : testStrings) {
            Matcher matcher = Pattern.compile(pattern).matcher(testString);
            if (matcher.find()) {
                System.out.println("'" + testString + "': 匹配到重复字符 " + matcher.group(0));
            } else {
                System.out.println("'" + testString + "': 没有匹配到重复字符");
            }
        }
    }
}

C#

using System;
using System.Text.RegularExpressions;

class Program {
    static void Main() {
        string pattern = @"(.)\1+";
        string[] testStrings = {"aaabbb", "abcd", "aabbcc", "helloo", "no_repeat"};
        
        foreach (string testString in testStrings) {
            Match match = Regex.Match(testString, pattern);
            if (match.Success) {
                Console.WriteLine($"'{testString}': 匹配到重复字符 {match.Value}");
            } else {
                Console.WriteLine($"'{testString}': 没有匹配到重复字符");
            }
        }
    }
}

PHP

<?php
$pattern = '/(.)\1+/';
$testStrings = ["aaabbb", "abcd", "aabbcc", "helloo", "no_repeat"];

foreach ($testStrings as $testString) {
    if (preg_match($pattern, $testString, $matches)) {
        echo "'$testString': 匹配到重复字符 $matches[0]\n";
    } else {
        echo "'$testString': 没有匹配到重复字符\n";
    }
}
?>

Ruby

pattern = /(.)\1+/
test_strings = ["aaabbb", "abcd", "aabbcc", "helloo", "no_repeat"]

test_strings.each do |test_string|
  match = pattern.match(test_string)
  if match
    puts "'#{test_string}': 匹配到重复字符 #{match[0]}"
  else
    puts "'#{test_string}': 没有匹配到重复字符"
  end
end