-3

I have a couple of strings and I want them to be transformed like shown below

In the first two examples " is included in the input string. But " does not comes always with the input string as shown in last two examples.

Basically I need the string between |" and "| or string between first and last occurrence of |

Can someone please let me know how to find the match for the output string that I need which will work for all of these strings? I am trying to code these in C#.

Thanks in advance for any help

Debesh Mohanty
  • 395
  • 1
  • 4
  • 15

3 Answers3

0

I would propose an alternative to regex. Simply using Substring and Replace:

List<string> input = new List<string>
{
    "501000061|\"B084PD449Q|2088|1\"|",
    "504000585|\"B000NSIAG0|3115|0\"|",
    "508000036|B084S1FVH5|42|1|",
    "504000584|B000NSIAG0|3115|0|"
};

foreach (var element in input)
{
    string transformed = element.Substring(10, element.Length - 11)
                                .Replace("\"", string.Empty);
    Console.WriteLine(transformed);
}

Output:

B084PD449Q|2088|1
B000NSIAG0|3115|0
B084S1FVH5|42|1
B000NSIAG0|3115|0

Mong Zhu
  • 20,890
  • 7
  • 33
  • 66
-1

^[0-9]{9}\|"?([A-Z0-9]){10}\|([0-9]){2,}\|([0-9])"?\|$

This regex is a bit more rigid than the ones already proposed based on the input examples that you've provided.

I suggest you look into non-regex solutions that have already been pointed out, however, if you absolutely must use regex here's how to do it in C# for this example.

  var pattern = @"^[0-9]{9}\|"?([A-Z0-9]){10}\|([0-9]){2,}\|([0-9])"?\|$";
  var replacement = "$1|$2|$3";
  var input = "501000061|\"B084PD449Q|2088|1\"|";
  var result = Regex.Replace(input, pattern, replacement);
Pavisa
  • 82
  • 7
-1

Here's one without regex:

using System;
using System.Linq;
                    
public class Program
{
    public static void Main()
    {
        var inp = "504000585|\"B000NSIAG0|3115|0\"|";
        
        var res = string
            .Join("|", inp.Split(new []{'|'}, StringSplitOptions.RemoveEmptyEntries).Skip(1))
            .Replace("\"", "");
        Console.WriteLine(res);
    }
}

https://dotnetfiddle.net/i39XUY

B000NSIAG0|3115|0
sommmen
  • 2,980
  • 1
  • 12
  • 23