java匹配多个空格,需要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:

我想確保我匹配的子字符串只有一個可能的標點符號和必要的空格。這是一個更長的REGEX,目前有以下內容:

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

在,,,, ,,,之前的字符串。 ....當我希望它匹配的字符串之后是字符串之前和字符串之后的任何數量的空格,只允許一個標點符號 - 請注意標點符號可以出現在字符串的開頭,最后,或者在之前或之后有盡可能多的空白。

3 个解决方案

#1

9

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字符串文字中,反斜杠需要轉義。

#2

0

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.

加號之前和之后的部分是匹配的字符串的其余部分。

#3

0

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

與你所放的基本相同,但必須匹配“一個可能的標點符號”而不是一個標點符號。加號表示它是較長正則表達式的一部分......

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值