c# - 将 C# 正则表达式转换为 Java 正则表达式

标签 c# java regex

任何简单的 unicode 字符串,如 Ë¡ÚËÌÌÌÌñânÊË 在 C# 正则表达式中使用以下模式进行匹配,但它们在 Java 中不匹配。

有人能解释一下吗?我如何纠正它以使其在 Java 中工作?

 "\\b[\\w\\p{M}\\u200B\\u200C\\u00AC\\u001F\\u200D\\u200E\\u200F]+\\b"

c# 代码:(它匹配字符串)

   private static readonly Regex s_regexEngine;


    private static readonly string s_wordPattern = @"\b[\w\p{M}\u200B\u200C\u00AC\u001F\u200D\u200E\u200F]+\b";

    static PersianWordTokenizer()
    {
        s_regexEngine = new Regex(s_wordPattern, RegexOptions.Multiline);
    }

    public static List<string> Tokenize(string text, bool removeSeparators, bool standardized)
    {
        List<string> tokens = new List<string>();

        int strIndex = 0;
        foreach (Match match in s_regexEngine.Matches(text))
        {
            //Enter in this block
        }

java代码:(它不匹配字符串)

 private static final String s_wordPattern = "\\b[\\w\\p{M}\\u200B\\u200C\\u00AC\\u001F\\u200D\\u200E\\u200F]+\\b";

static
{
    s_regexpattern = Pattern.compile(Pattern.quote(s_wordPattern));
}

public static java.util.ArrayList<String> Tokenize(String text, boolean removeSeparators, boolean standardized)
{
    java.util.ArrayList<String> tokens = new java.util.ArrayList<String>();

    int strIndex = 0;
    s_regexEngine=s_regexpattern.matcher(text);
    while(s_regexEngine.find())
    {
              // it dosnt enter in this block
            }

最佳答案

查看“任意字母”unicode 字符类 \p{L},或者查看 java Pattern.compile 方法的 Pattern.UNICODE_CHARACTER_CLASS 参数。

我想第二个,因为仅是 Java,你不会感兴趣,但值得一提。

import java.util.regex.Pattern;

/**
 * @author Luc
 */
public class Test {

  /**
   * @param args
   */
  public static void main(final String[] args) {

    test("Bonjour");

    test("یسیتنانت");

    test("世界人权宣言 ");
  }

  private static void test(final String text) {

    showMatch(Pattern.compile("\\b\\p{L}+\\b"), text);

    showMatch(Pattern.compile("\\b\\w+\\b", Pattern.UNICODE_CHARACTER_CLASS), text);
  }

  private static void showMatch(final Pattern pattern, final String text) {

    System.out.println("With pattern \"" + pattern + "\": " + text + " " + pattern.matcher(text).find());
  }

}

结果:

With pattern "\b\w+\b": Bonjour true
With pattern "\b\p{L}+\b": Bonjour true
With pattern "\b\w+\b": یسیتنانت true
With pattern "\b\p{L}+\b": یسیتنانت true
With pattern "\b\w+\b": 世界人权宣言  true
With pattern "\b\p{L}+\b": 世界人权宣言  true

关于c# - 将 C# 正则表达式转换为 Java 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14280005/

相关文章:

C# 字符无法正确计数(算法)

c# - 单击它更改内容并返回原始状态的按钮

java - JAVA以表格形式保存数据(用户统计)

javascript - 语言代码剥离正则表达式

c# - c# 中的 Async 和 yield 关键字

java - 将 ssl 证书添加到 selenium-webdriver

java - 通过Python子进程读取Java system.out.print

Java正则表达式与问号和单词边界完全匹配

javascript - jQuery:搜索包含特定标记的 div

c# - 如果任务是在 C# 中编写 hello world...使用反射,那么使用反射的一些巧妙方法是什么?