Regular Expressions separated by commas (,)

Source: Internet
Author: User

Let's give an example first.

Has the following strings:

"Reservation, Marshal, type"

I want to convert the string to an array using a comma. Needless to say, there is a simplest method, which can be easily done using string. Split (New char.

 
String [] STRs = string. Split (New char [] {','}; foreach (string STR in STRs ){//...}

 

But what if a certain data contains a number? For example:

"Reser, vation, Marshal, type"

Assume that Reser and vation are complete data. If we use the above method, a big problem will occur. If you can use a mark such as \, to keep the mark in the data, rather than as a tag to separate strings.

So I thought about it and tried to use a regular expression to solve this problem. FirstCodePaste it here. I don't know if there is a better way.

VaR spliters = RegEx. Split (values, @ "([^ \],)");
 
For (INT I = 0; I & lt; spliters. length; ++ I) {if (I % 2 = 1) {spliters [I-1] + = spliters [I]. substring (0, 1); spliters [I] = spliters [I]. substring (1 );}}
 
Suppose I use the regular expression above to analyze the data.
"Reser \, vation, Marshal, type"
 
The result is displayed.
 
Reser \, Vati
 
N,
Marshal
 
,
 
Type
 
You will find that the first N and number are captured as separators. This is obviously not what I need, so I used the for loop below to correct the data.
For (INT I = 0; I <spliters. length; ++ I) {if (I % 2 = 1) {spliters [I-1] + = spliters [I]. substring (0, 1); spliters [I] = spliters [I]. substring (1 );}}

 

The corrected result is:

Reser \, vation

,

Marshal

,

Type

I wonder if you have any better ideas. Thank you.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.