字符类减法 [英] Character class subtraction

查看:72
本文介绍了字符类减法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用特定模式尝试获得没有标点符号的句子。
我有这个:

I'm using a specific pattern in attempt to get a sentence without the punctuation. I have this:

 p = Pattern.compile("[\\p{Punct}\\s]+");
 String[] all = p.split("int a = 4;");

我得到数组

all = {int, a, 4};

这很棒,但我希望我的模式也保持[](如果存在)。例如:

That is great but I want my pattern to also keep "[]" if it exists. for example:

String[] all = p.split("int[] a = 4;");

并获得

all = {int,[], a, 4};

这是我希望模式添加[]的唯一改变。
有没有办法做到这一点?

That is the only change thing I want the pattern to add the "[]" nothing else. Any way to do that?

推荐答案

试试这个:

Pattern p = Pattern.compile("[[\\p{Punct}&&[^\\[\\]]]\\s]+");

[] 字符被视为标点字符。在拆分字符串时,此正则表达式将排除它们。

The [ and ] characters are considered as punctuation characters. This regex will exclude them when splitting the string.

这篇关于字符类减法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆