【问题标题】:Split a string by another string except by [duplicate]用另一个字符串拆分一个字符串,除了 [duplicate]
【发布时间】:2020-03-12 08:10:03
【问题描述】:

我想使用分隔符: 使用正则表达式拆分此行,除非该段包含?:

string input = "AV Rocket 456:Contact?:Jane or Tarza:URL?:http?://www.jane.com:Delivered 18?:15:Product Description";

我试过了

string pattern = @"[^\?:]\:";

但是所有元素的最后一个字符都被剪掉了,

我在等待这个结果:

“AV 火箭 456”
“联系方式?:简或泰山”
'URL?:http?://www.jane.com'
'交货时间 18?:15'
'产品 说明'

https://dotnetfiddle.net/PeVuMM

【问题讨论】:

  • 你的意思是你需要像“AV Rocket 456:”这样的输出?
  • string pattern = @"(?<!\?):";
  • @AlexanderPetrov:将此评论作为答案。

标签: c# regex split except


【解决方案1】:

如果我理解了您的问题,下面的示例将给出预期的输出:)

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Xunit;

namespace XUnitTestProject1
{
    public class UnitTest1
    {
        [Fact]
        public void TestPatternSplit()
        {

            var input = @"AV Rocket 456:Contact?:Jane or Tarzan:URL?:http?://www.jane.com:Time Delivered 18?:15:Product Description";

            var output = PatternSplit(input);

            var expected = new[]{"AV Rocket 456", "Contact?:Jane or Tarzan", "URL?:http?://www.jane.com","Time Delivered 18?:15","Product Description"};

            Assert.Equal(expected, output);

        }

        private static IEnumerable<string> PatternSplit(string input)
        {
            const string  pattern = @"(?<!\?):";
            return Regex.Split(input, pattern);
        }
    }
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-17
相关资源
最近更新 更多