开发者

C# Rearrange text in a string

开发者 https://www.devze.com 2023-04-03 02:05 出处:网络
I have a text with customer information and the information comes in different format and I would like to rearrange the costomer information so all the information looks the same before parsing.

I have a text with customer information and the information comes in different format and I would like to rearrange the costomer information so all the information looks the same before parsing.

The customer information format 1:

ID: 1
Name: A
Last name: B

The customer information format 2:

ID: 
1
Name: 开发者_开发百科
A
Last name: 
B

Is there any way to so that I rearrange the information so they all looks like the example number 1?

All help is very appreciated.


It looks like you may just need:

text = text.Replace(": \r\n", ": ");

That would work for the example you've given, possibly having changed "\r\n" to "\n" depending on the exact format.


This is a bit more flexible that the simple replacement of ": \r\n", but it can't really ever be perfect

 Regex.Replace(input,@"(:\s*)\n([^:]*$)","$1$2",RegexOptions.Multiline);

It finds a : followed by 0 or more whitespace characters, followed by a newline, followed by a line containing no colons, and removes the newline in this case. The only advantage over Jon's answer is that it will work with empty value, ie:

ID: 
1
Name: 
A
Middle Name:
Last name: 
B

becomes

ID: 1
Name: A
Middle Name:
Last name: B

It's OK if thats a requirement, but a lot more complex if not!


It would be difficult to write single generic code for any type of format.

However, you could write an interface with a method say Format(...) and create one class for each type of format then instantiate object of class accordingly.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号