【问题标题】:tokenize a string with regex having special characters使用具有特殊字符的正则表达式标记字符串
【发布时间】:2017-04-24 17:33:39
【问题描述】:

我正在尝试在包含单词、数字和特殊字符的字符串中查找标记。我尝试了以下代码:

String Pattern = "(\\s)+";
String Example = "This `99 is my small \"yy\"  xx`example ";
String[] splitString = (Example.split(Pattern));
System.out.println(splitString.length);
for (String string : splitString) {
    System.out.println(string);
}

得到以下输出:

This:`99:is:my:small:"yy":xx`example:

但我真正想要的是这个,即我希望特殊字符也作为单独的标记:

This:`:99:is:my:small:":yy:":xx:`:example:

我尝试将特殊字符放入模式中,但现在特殊字符完全消失了:

String Pattern = "(\"|`|\\.|\\s+)";
This::99:is:my:small::yy::xx:example:

我将通过什么模式获得我想要的输出?还是我应该尝试一种不同于使用正则表达式的方法?

【问题讨论】:

  • ideone.com/lm0ioP_ 呢,对你来说是不是特别的字符?
  • @WiktorStribiżew 的答案是正确的,因为 " 也应该是“标记化”的,但在 OP 的输出中,对于 \"yy\",以下字符串应该是 ":yy:"。在这种情况下,请在第 13 行使用Pattern ptrn = Pattern.compile("(\"(?:[\\w]+|[\\d]+)\"|\\b[\\w\\d]+|[^\\s])");
  • @Mateus:我已经接受了 WiktorStribiżew 给出的答案,但是你的正则表达式版本对我来说更好,因为我在这里得到了 example_and_more。谢谢。

标签: java regex


【解决方案1】:

您可以使用匹配方法来匹配字母条纹(带有或不带有组合标记)、数字或单个字符,而不是单词和空格。我认为_ 在这种方法中应该被视为一个特殊的字符。

使用

"(?U)(?>[^\\W\\d]\\p{M}*+)+|\\d+|[^\\w\\s]"

请参阅regex demo

详情

  • (?U) - Pattern.UNICODE_CHARACTER_CLASS 修饰符的内联版本
  • (?>[^\\W\\d]\\p{M}*+)+ - 1 个或多个字母或 _ 后面有/没有组合标记
  • | - 或
  • \\d+ - 任何 1 位以上的数字
  • | - 或
  • [^\\w\\s] - 单个字符,可以是除单词和空格之外的任何字符。

Java demo

String str = "This `99 is my small \"yy\"  xx`example_and_more ";
Pattern ptrn = Pattern.compile("(?U)(?>[^\\W\\d]\\p{M}*+)+|\\d+|[^\\w\\s]");
List<String> res = new ArrayList<>();
Matcher matcher = ptrn.matcher(str);
while (matcher.find()) {
    res.add(matcher.group());
}
System.out.println(res);
// => [This, `, 99, is, my, small, ", yy, ", xx, `, example_and_more]

【讨论】:

  • 太好了,谢谢!这给出了输出 [This, , 99, is, my, small, ", yy, ", xx, , example, , and, _, more],但我更喜欢 [This, , 99, is, my, small, ", yy, ", xx, , example_and_more],即“”与“w”。有没有正则表达式可以做到这一点?
  • 是的,当然,我提到了_的问题:它是\w\p{Punct}的一部分,它取决于实际需要如何处理。
猜你喜欢
  • 2022-11-16
  • 2023-03-04
  • 1970-01-01
  • 1970-01-01
  • 2016-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多