任何简单的 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/