【问题标题】:Splitting String in regex with - as one word将正则表达式中的字符串与 - 作为一个单词
【发布时间】:2018-12-03 20:24:19
【问题描述】:

我试图在每组正则表达式中用 32 个字符分割一个句子。如果第 32 个字符是单词中的字母,则句子在完整单词后拆分。当我的输入是一个带有“-”的句子时,它也会拆分该单词。

这是我正在使用的正则表达式

(\b.{1,32}\b\W?)

输入字符串:

Half Bone-in Spiral int with dark Packd Smithfield Half 带骨螺旋火腿配釉包

结果组:

  1. 半骨螺旋 int with
  2. dark Packd Smithfield 半骨-
  3. 带釉包装的螺旋火腿

在上面的拆分中,“Bone-in”是一个单词,但正则表达式会考虑单独的单词来拆分它。如何修改我的正则表达式以将“-”视为一个词?总之,我想要Bone-in之后的分裂。

谢谢。

【问题讨论】:

  • 试试(\b.{32,}?\b(?:-\w+)?\W*)
  • 上面的正则表达式忽略了句子的最后一部分,它没有 32 个字符
  • 是的,但是当你用它拆分时(在大多数语言中),最后一部分仍然存在。
  • 我在 java 中使用 Pattern 并且忽略了句子的最后一部分
  • 那就试试(\b.{1,32}(?![\w-])\W?)

标签: java regex string punctuation


【解决方案1】:

你可以使用

(\b.{1,32}(?![\w-])\W?)

详情

  • \b - 单词边界
  • .{1,32} - 1 到 32 个字符(换行符除外),尽可能多
  • (?![\w-]) - 当前位置左侧的字符不能是单词(字母、数字或_)或- char
  • \W? - 一个可选的非单词字符。

在 Java 中,使用以下方法:

public static String[] splitIncludeDelimeter(String regex, String text){
    List<String> list = new LinkedList<>();
    Matcher matcher = Pattern.compile(regex).matcher(text);

    int now, old = 0;
    while(matcher.find()){
        now = matcher.end();
        list.add(text.substring(old, now));
        old = now;
    }

    if(list.size() == 0)
        return new String[]{text};

    //adding rest of a text as last element
    String finalElement = text.substring(old);
    list.add(finalElement);

    return list.toArray(new String[list.size()]);
}

Java example:

String s = "Half Bone-in Spiral int with dark Packd Smithfield Half Bone-in Spiral Ham with Glaze Pack";
String[] res = splitIncludeDelimeter("(\\b.{1,32}(?![\\w-])\\W?)", s);
System.out.println(Arrays.toString(res));
// => [Half Bone-in Spiral int with , dark Packd Smithfield Half , Bone-in Spiral Ham with Glaze , Pack, ]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多