匹配中文字符

2024-06-23 21:13:46 439
匹配中文字符的正则表达式与解析,包含Python、JavaScript、Java、C#等使用案例

正则表达式

[\u4e00-\u9fa5]

解释

  • [\u4e00-\u9fa5]:匹配任意一个Unicode范围在4E009FA5之间的中文字符。

用法

Python

import re

pattern = r'[\u4e00-\u9fa5]'
test_strings = ["你好", "Hello", "世界"]

for test_string in test_strings:
    if re.search(pattern, test_string):
        print(f"'{test_string}': 包含中文字符")
    else:
        print(f"'{test_string}': 不包含中文字符")

JavaScript

const pattern = /[\u4e00-\u9fa5]/;
const testStrings = ["你好", "Hello", "世界"];

testStrings.forEach(testString => {
    if (pattern.test(testString)) {
        console.log(`'${testString}': 包含中文字符`);
    } else {
        console.log(`'${testString}': 不包含中文字符`);
    }
});

Java

import java.util.regex.*;

public class RegexTest {
    public static void main(String[] args) {
        String pattern = "[\\u4e00-\\u9fa5]";
        String[] testStrings = {"你好", "Hello", "世界"};
        
        for (String testString : testStrings) {
            if (Pattern.compile(pattern).matcher(testString).find()) {
                System.out.println("'" + testString + "': 包含中文字符");
            } else {
                System.out.println("'" + testString + "': 不包含中文字符");
            }
        }
    }
}

C#

using System;
using System.Text.RegularExpressions;

class Program {
    static void Main() {
        string pattern = "[\u4e00-\u9fa5]";
        string[] testStrings = {"你好", "Hello", "世界"};
        
        foreach (string testString in testStrings) {
            if (Regex.IsMatch(testString, pattern)) {
                Console.WriteLine($"'{testString}': 包含中文字符");
            } else {
                Console.WriteLine($"'{testString}': 不包含中文字符");
            }
        }
    }
}

PHP

<?php
$pattern = '/[\x{4e00}-\x{9fa5}]/u';
$testStrings = ["你好", "Hello", "世界"];

foreach ($testStrings as $testString) {
    if (preg_match($pattern, $testString)) {
        echo "'$testString': 包含中文字符\n";
    } else {
        echo "'$testString': 不包含中文字符\n";
    }
}
?>

Ruby

pattern = /[\u4e00-\u9fa5]/
test_strings = ["你好", "Hello", "世界"]

test_strings.each do |test_string|
  if pattern.match?(test_string)
    puts "'#{test_string}': 包含中文字符"
  else
    puts "'#{test_string}': 不包含中文字符"
  end
end