简体   繁体   English

需要java regex来匹配具有多个空格的子字符串,只需要一个标点符号

[英]Need java regex to match substring with multiple whitespace, only one punctuation

I want to make sure that the substring I am matching only has one possible piece of punctuation and as much whitespace as necessary. 我想确保我匹配的子字符串只有一个可能的标点符号和必要的空格。 This is inside of a much longer REGEX, currently what there is is the following: 这是一个更长的REGEX,目前有以下内容:

[\\p{P},\\s] [\\ p {P},\\ s]的

but that will match all punctuation and whitespace, so that it accepts: 但这将匹配所有标点符号和空格,以便它接受:

the string before,,,, ,,,. 在,,,, ,,,之前的字符串。 ....the string after when 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- note that the punctuation can come at the beginning of the string, at the end, or with as much whitespace before or after. ....当我希望它匹配的字符串之后是字符串之前和字符串之后的任何数量的空格,只允许一个标点符号 - 请注意标点符号可以出现在字符串的开头,最后,或在之前或之后有尽可能多的空白。

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 我希望它匹配的是字符串之前和字符串之后的任何数量的空格,只允许一个标点符号项

Try this: 尝试这个:

\s*\p{P}\s*

Explanation: 说明:

\s*   Match any amount of whitespace
\p{P} Match a single punctuation character
\s*   Match any amount of whitespace

Note that in Java string literals the backslashes need escaping. 请注意,在Java字符串文字中,反斜杠需要转义。

oops, I think I found it myself - at any rate it seems to work with various combinations of whitespace and punctuation: 哎呀,我想我自己找到了 - 无论如何它似乎与空白和标点符号的各种组合一起工作:

+(\s*)+(\p{P})?+(\s)+

with the parts before and after the plus signs being the rest of the string being matched. 加号之前和之后的部分是匹配的字符串的其余部分。

Yeah you're right it was redundant 是的,你是对的,这是多余的

it should be 它应该是

\s*(\p{P})?\s

basically the same as what you put, but has to match 'one possible piece of punctuation' not one required piece of punctuation. 与你所放的基本相同,但必须匹配'一个可能的标点符号'而不是一个标点符号。 The plus signs were put in to indicate that it was part of a longer regex... 加号表示它是较长正则表达式的一部分......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM