我想确保我匹配的子字符串只有一种可能的标点符号和尽可能多的空格。这是一个更长的 REGEX 内部,目前有以下内容:
[\p{P},\s]
但这将匹配所有标点符号和空格,因此它接受:
,,,, ,,, 之前的字符串。 ....之后的字符串 当我希望它匹配的是之前字符串和之后字符串之间的任意数量的空格时,只允许使用一个标点符号 - 请注意,标点符号可以出现在字符串的开头、结尾或作为之前或之后有很多空白。
最佳答案
what I want it to match is any amount of whitespace in between the string before and the string after, with only one item of punctuation allowed
试试这个:
\s*\p{P}\s*
解释:
\s* Match any amount of whitespace \p{P} Match a single punctuation character \s* Match any amount of whitespace
请注意,在 Java 字符串文字中,反斜杠需要转义。
关于java - 需要 java 正则表达式来匹配具有多个空格的子字符串,只有一个标点符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2757529/