给定如下所示的字符串,通过正则表达式删除所有前导和尾随标点符号:
String a = "!?Don't.;, .:delete !the@ $actual string%";
String b = "Hyphenated-words, too!";
我知道正则表达式 [\P{Alnum}] 将定位所有非字母数字字符,但是如何仅定位前导和尾随标点符号,以便我得到...
a = "Don't delete the actual string";
b = "Hyphenated-words too";
...而不是:
a = "Dont delete the actual string";
b = "Hyphenated words too";
我只需要正则表达式;不是删除标点符号的实际代码。
最佳答案
您想要匹配与 a) 空白字符或 b) 开头或结尾相邻的标点符号。
您的模式前面带有
(?<=^|\s)
正向回顾,或您的模式后跟
(?=\s|$)
积极的前瞻
为了缩短模式,我们可以稍微改写一下,即我们的标点符号 block 必须 a) 前面不能有非空白字符,或者 b) 后面不能有非空白字符。
您的模式前面带有
(?<!\S)
负向回顾,或您的模式后跟
(?!\S)
负前瞻
最后一点,您应该使用 \p{Punct}
而不是[\P{Alnum}]
以匹配标点符号。请参阅comment by sln了解详情。
这是一个示例用法:
String a = "!?Don't.;, .:delete !the@ $actual string%";
String b = "Hyphenated-words, too!";
String regex = "(?:(?<!\\S)\\p{Punct}+)|(?:\\p{Punct}+(?!\\S))";
System.out.println(a.replaceAll(regex, ""));
System.out.println(b.replaceAll(regex, ""));
输出:
Don't delete the actual string
Hyphenated-words too
关于java - 如何使用正则表达式从字符串中删除外部标点符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43171774/