Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

regex

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:

[\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.

like image 456
user254694 Avatar asked Jan 22 '23 03:01

user254694


1 Answers

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.

like image 75
Mark Byers Avatar answered Feb 08 '23 10:02

Mark Byers