Unicode或特殊字符的Java Regex

时间:2019-06-27 21:04:29

标签: java regex unicode

我在Javascript(NodeJS)中有以下声明-

const name = (name) =>
 name && !XRegExp('^[\\p{L}\'\\d][ \\p{L}\'\\d-]*[\\p{L}\'-\'\\d]$').test(name)
? 'Invalid' : undefined

此正则表达式用于名称,可以接受.-(空格),并且应以字符开头。

如何在Java中实现相同的验证正则表达式。我在下面尝试过-

@Pattern(regexp = "^(?U)[\\p{L}\\'\\d][ \\p{L}\\'\\d-]*[\\p{L}\\'-\\'\\d]$" , 
message="Invalid name")
String name;

1 个答案:

答案 0 :(得分:1)

根据您提供的内容,我猜想这种表达方式可能有效:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "^[\\p{L}\\d'][ \\p{L}\\d'-]*[\\p{L}\\d'-]$";
final String string = "éééééé";

final Pattern pattern = Pattern.compile(regex, Pattern.UNICODE_CHARACTER_CLASS);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println("Full match: " + matcher.group(0));
    for (int i = 1; i <= matcher.groupCount(); i++) {
        System.out.println("Group " + i + ": " + matcher.group(i));
    }
}

DEMO