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

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

问题描述

我想使用 Regex 类中的 Split 函数拆分字符串.问题是它删除分隔符,我想保留它们.最好作为被拆分对象中的单独元素.

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:split(/(.)/g, "123.456.789")

(虽然不是 Java)

(Not Java though)

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

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