-5

sample data = "KRIS, KUMAR ( 46 0230 A"

code

var name = data.Replace("\n","");
Regex  rgx = new Regex("[^a-zA-Z,]");
data = rgx.Replace(data,"");

output - KRIS,KUMARA

expected op - KRIS, KUMAR A

Krishna Mohan
  • 175
  • 1
  • 6
  • 14
  • You can use something like `string.Join(", ", Regex.Matches(data, @"\p{L}+").Cast().Select(x => x.Value).ToArray())`. It can also be done without regex, if it is what you want. – Wiktor Stribiżew Aug 30 '23 at 18:48
  • this code will not work for KRIS KUMAR . i don't want to add comma in every end of string. it will treat "KRIS" as a last name.im splitting the string and checking comma is there or not, based on that im assigning first name and last name – Krishna Mohan Aug 30 '23 at 19:14
  • So, you can just use something like `var match = Regex.Match(data, @"(\p{L}+)\P{L}+(\p{L}+)\P{L}+(\p{L}+)"); if (match.Success()) { Console.WriteLine(match.Groups[1].Value); Console.WriteLine(match.Groups[2].Value); Console.WriteLine(match.Groups[3].Value);}` – Wiktor Stribiżew Aug 30 '23 at 19:37
  • What exactly do you mean by "special characters"? – CAustin Aug 30 '23 at 20:16
  • Your regex doesn't keep spaces so the output won't have any. If you do keep spaces there will be a whole bunch between `KUMAR` and `A`. So that means you need two regex - one that keeps all the spaces and one that reduces multiple spaces to a single space. Something like `var name = data.Replace("\n","");Regex rgx1 = new Regex("[^a-zA-Z,]");data = rgx1.Replace(data,"");Regex rgx2 = new Regex(" +");data = rgx2.Replace(data," ");` – Jerry Jeremiah Aug 30 '23 at 21:38
  • Maybe something like `([\p{L}, ]*)([^\p{L}, \r\n]+ ?)` with a replacement of `$1`. Test it here: https://regex101.com/r/x3cfup/2 – Patrick Janser Aug 31 '23 at 15:01

0 Answers0