【问题标题】:Split string on a Regex在正则表达式上拆分字符串
【发布时间】:2019-12-24 10:36:48
【问题描述】:

我有以下字符串

  1. mo474334pt1572
  2. at1088ma15
  3. ma15pt1983
  4. ca1

我要获得

a) string[] result = new[] {"mo474334", "pt1572"};
a) string[] result = new[] {"at1088", "ma15"};
a) string[] result = new[] {"ma15", "pt1983"};
c) string[] result = new[] {"ca1"};

我一直在尝试以下方法,但收效甚微

string[] result = Regex.Split(str, @"\[A-Za-z]{2}[0-9]*");

string[] result = Regex.Split(str, @"\[A-Za-z]{2}[0-9]*\[A-Za-z]{2}[0-9]*");

string[] result = Regex.Matches(str, @"^[A-Za-z]{2}[0-9]*").Cast<Match>().Select(m => m.Value).ToArray();

谁能看到我哪里出错了,这可以实现吗?或者我应该使用其他方法

【问题讨论】:

  • 您可以在边界数字/字母上拆分:(?&lt;=\d)(?=[a-z]

标签: c# .net regex


【解决方案1】:

您可以匹配 2 次字符 a-zA-Z 和 1 个或多个数字 0-9

,而不是拆分
[A-Za-z]{2}[0-9]+

Regex demo | C# demo


如果您想使用拆分,一种方法是使用正向前瞻

\B(?=[A-Za-z]{2}[0-9])
  • \B 断言词边界不匹配的位置
  • (?= 正向前瞻,断言右边是
    • [A-Za-z]{2}[0-9] 匹配 2 次 char a-zA-Z
  • )关闭前瞻

Regex demo | C# demo

【讨论】:

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