java - 正则表达式 + Java : split a text into words and removing punctuation only if they are alone or at the end

标签 java regex

我正在尝试将字符串拆分为单词,但我想将“a.b.c”保留为单词,并且仅在标点符号单独存在或位于单词末尾时才删除标点符号 例如

"a.b.c" --> "a.b.c"
"a.b."  --> "a.b"

例如

String str1 = "abc a.b a. .  b, , test"; should return "abc","a.b","a","b","test"

最佳答案

您可以使用:

String str1 = "abc a.b a. .  b, , test";
String[] toks = str1.split("\\p{Punct}*\\s+[\\s\\p{Punct}]*");
for (String tok: toks)
    System.out.printf(">>> [%s]%n", tok);

>>> [abc]
>>> [a.b]
>>> [a]
>>> [b]
>>> [test]

关于java - 正则表达式 + Java : split a text into words and removing punctuation only if they are alone or at the end,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26288956/

相关文章:

java - Java 中的正弦波声音发生器

java - 使用迭代器时出现 java.util.LinkedList$ListItr.checkForComodification 异常?

regex - Htaccess - 用正斜杠替换 .html

python - 用于过滤与模式匹配的字符串列表的正则表达式

C++ 正则表达式 : Get index of the Capture Group the SubMatch matched to

java - Android kotlin/java - ReclerView 在 Holder/xml 中隐藏部件时的奇怪行为

java - 在 Hibernate 映射中将 VARCHAR 转换为整数

java - 在 Apache POI 中移动单元格

regex - 重复捕获组忽略空格

python正则表达式重复字符