Man*_*erc 5 java regex split symbols latin
我需要拆分文本并仅获取单词、数字和连字符组成的单词。我还需要获取拉丁词,然后我使用了\\p{L},它给了我 \xc3\xa9、\xc3\xba \xc3\xbc \xc3\xa3 等等。例子是:
String myText = "Some latin text with symbols, ? 987 (A la pointe sud-est de l\'\xc3\xaele se dresse la cath\xc3\xa9drale Notre-Dame qui fut lors de son ach\xc3\xa8vement en 1330 l\'une des plus grandes cath\xc3\xa9drales d\'occident) : ! @ # $ % ^& * ( ) + - _ #$% " \' : ; > < / \\ | , here some is wrong\xe2\x80\xa6 * + () e -"\n\nPattern pattern = Pattern.compile("[^\\\\p{L}+(\\\\-\\\\p{L}+)*\\\\d]+");\nString words[] = pattern.split( myText );\nRun Code Online (Sandbox Code Playgroud)\n\n这个正则表达式有什么问题?"("为什么它匹配、"+"、"-"、"*"等符号"|"?
一些结果是:
\n\ndresse // OK\nsud-est // OK\noccident) // WRONG\n987 // OK\n() // WRONG\n(a // WRONG\n* // WRONG\n- // WRONG\n+ // WRONG\n( // WRONG\n| // WRONG\nRun Code Online (Sandbox Code Playgroud)\n\n正则表达式的解释是:
\n\n[^\\p{L}+(\\-\\p{L}+)*\\d]+\n\n * Word separator will be:\n * [^ ... ] No sequence in:\n * \\p{L}+ Any latin letter\n * (\\-\\p{L}+)* Optionally hyphenated\n * \\d or numbers\n * [ ... ]+ once or more.\nRun Code Online (Sandbox Code Playgroud)\n
如果我对您的要求的理解是正确的,这个正则表达式将匹配您想要的:
"\\p{IsLatin}+(?:-\\p{IsLatin}+)*|\\d+"
Run Code Online (Sandbox Code Playgroud)
它将匹配:
\p{L}字母中的字母。如果您的 Java 版本不支持该语法,请更改为。\\p{IsLatin}\\pL上面的正则表达式是通过调用Pattern.compile, 和 callmatcher(String input)来使用来获取Matcher对象,并使用循环来查找匹配项。
Pattern pattern = Pattern.compile("\\p{IsLatin}+(?:-\\p{IsLatin}+)*|\\d+");
Matcher matcher = pattern.matcher(inputString);
while (matcher.find()) {
System.out.println(matcher.group());
}
Run Code Online (Sandbox Code Playgroud)
如果您想允许带有撇号的单词':
"\\p{IsLatin}+(?:['\\-]\\p{IsLatin}+)*|\\d+"
Run Code Online (Sandbox Code Playgroud)
我还在-角色类中转义['\\-],以防万一您想添加更多内容。如果它是字符类中的第一个或最后一个,实际上-不需要转义,但为了安全起见,我还是转义了它。