如何保持Regex.Split的分隔符? [英] How to keep the delimiters of Regex.Split?

查看:1031
本文介绍了如何保持Regex.Split的分隔符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想分开使用拆分正则表达式类函数的字符串。问题是,它的删除分隔符,我想留住他们。 preferably作为splitee单独的元素。

I'd like to split a string using the Split function in the Regex class. The problem is that it removes the delimiters and I'd like to keep them. Preferably as separate elements in the splitee.

根据其他讨论中我发现,只有不便的方式来实现这一点。

According to other discussions that I've found, there are only inconvenient ways to achieve that.

有什么建议?

推荐答案

只要把图案变成捕获组,比赛也将包括在结果中。

Just put the pattern into a capture-group, and the matches will also be included in the result.

string[] result = Regex.Split("123.456.789", @"(\.)");

结果:

{ "123", ".", "456", ".", "789" }

这也适用于许多其他语言:

This also works for many other languages:


  • 的JavaScript 123.456.789.split(/(\\.)/ G)

  • 的Python re.split(R。(\\),123.456.789)

  • 的Perl 拆分(/(\\.)/克,123.456.789)

  • JavaScript: "123.456.789".split(/(\.)/g)
  • Python: re.split(r"(\.)", "123.456.789")
  • Perl: split(/(\.)/g, "123.456.789")

(不是Java虽然)

这篇关于如何保持Regex.Split的分隔符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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