Java regex needs to match a substring with multiple spaces, only one punctuation

I want to make sure that the substring in which I match has only one possible punctuation fragment and as many spaces as necessary. This is inside the much longer REGEX, currently the following exists:

[\ p {P}, \ s]

but this will fit all punctuation and spaces so that it accepts:

the line before ,,,, ..... the line after when what I want it to match is any number of spaces between the line before and after the line, with only one punctuation point - note that punctuation can be at the beginning lines at the end or using many spaces before or after.

+4
source share
3 answers

what I want it to match is any number of spaces between the line before and after the line, with only one punctuation clause

Try the following:

\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, backslashes require escaping.

+9
source

Oops, I think I found it myself - in any case, it seems that it works with various combinations of spaces and punctuation marks:

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

with parts before and after the plus signs that correspond to the remaining line.

0
source

Yeah you're right he was superfluous

he should be

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

basically the same as you, but should match β€œone possible piece of punctuation,” not the mandatory part of punctuation. Plus signs were introduced to indicate that it was part of a longer regular expression ...

0
source

Source: https://habr.com/ru/post/1308650/


All Articles