微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

需要C#Regex才能在句子中获得单词对

是否有正则表达式将采取以下句子:

“我想把它分成两对”

生成以下列表:

“我想要”,
“想要这个”,
“这种分裂”,
“分开”,
“进入”,
“成对”

解决方法

由于需要重复使用单词,因此需要先行断言:
Regex regexObj = new Regex(
    @"(     # Match and capture in backreference no. 1:
     \w+    # one or more alphanumeric characters
     \s+    # one or more whitespace characters.
    )       # End of capturing group 1.
    (?=     # Assert that there follows...
     (\w+)  # another word; capture that into backref 2.
    )       # End of lookahead.",RegexOptions.IgnorePatternWhitespace);
Match matchResult = regexObj.Match(subjectString);
while (matchResult.Success) {
    resultList.Add(matchResult.Groups[1].Value + matchResult.Groups[2].Value);
    matchResult = matchResult.Nextmatch();
}

对于三人组:

Regex regexObj = new Regex(
    @"(     # Match and capture in backreference no. 1:
     \w+    # one or more alphanumeric characters
     \s+    # one or more whitespace characters.
    )       # End of capturing group 1.
    (?=     # Assert that there follows...
     (      # and capture...
      \w+   # another word,\s+   # whitespace,\w+   # word.
     )      # End of capturing group 2.
    )       # End of lookahead.",RegexOptions.IgnorePatternWhitespace);

等等

原文地址:https://www.jb51.cc/c/112555.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐