使用正则表达式和csv引用字符串

时间:2015-10-07 22:37:45

标签: c# regex

我正在尝试转换像

这样的字符串
"test",645,23.4,42,"13,13,14","test"

进入

"test","645","23.4","42","13,13,14","test"

我正在尝试使用此代码。

string pattern = "\",(? !\")";
string pattern2 = "(?<!\"),(? !\")";
string pattern3 = "(?<!\"),\"";
string replacement = "\",\"";

Regex rgx = new Regex(pattern);
catalogo = rgx.Replace(catalogo, replacement);
rgx = new Regex(pattern2);
catalogo = rgx.Replace(catalogo, replacement);
rgx = new Regex(pattern3);
catalogo = rgx.Replace(catalogo, replacement);

但我不知道如何超越已包含逗号的值。 "13,13,14"因为它会将其更改为"13","13","14"

我不知道这是否是转换字符串的最佳方式,但至少我相信它会完成这项工作,只是因为我不知道为什么我会过去这个。

1 个答案:

答案 0 :(得分:4)

我不确定为什么你需要使用正则表达式来解析逗号分隔的数据 有很多免费的库专门解析这种数据,同一个.NET Framework在Microsoft.VisualBasic.IO命名空间中提供了一个特定的类

在这里你可以如何使用它

#import "TableViewController.h"
#import "TableCell.h"

@interface TableViewController ()
{
    NSMutableData *webData;
    NSURLConnection *connection;
    NSMutableArray *array;
}

@end

@implementation TableViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    // Get an array from web and Populate Check Arrays with New Data as above ...

    [self GetDatabaseData];
}

-(void)GetDatabaseData{
    NSURL *blogURL = [NSURL URLWithString:JSON_URL];
    NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];
    NSError *error = nil;

    //NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData: jsonData options:0 error:&error];
    NSArray *TransactionArray = [NSJSONSerialization JSONObjectWithData: jsonData options:0 error:&error];

    NSDecimalNumber *check_total = [NSDecimalNumber zero];

    NSString *current_check;

    // Loop through Json objects, create question objects and add them to our questions array
    for (int i = 0; i < TransactionArray.count; i++)
    {
        NSDictionary *jsonElement = TransactionArray[i];

        // Accumulate if this is part of the same check.
       NSDecimalNumber *line_total = [NSDecimalNumber decimalNumberWithString:jsonElement[@"tran_value"]];

        // Decide if this is Element Belong to the Last Check number.
        if (jsonElement[@"tran_check"] == current_check){
            check_total = line_total; // Reset Check Total to be the Value of this Line on NEW Checks
        }
        else{
           check_total = [check_total decimalNumberByAdding:line_total];     //Add this Line Value to the Running Check Total
        }

        current_check = jsonElement[@"tran_check"]; // Make this Check number the Current Check for Totalizing.

        _Checknumbers = @[jsonElement[@"tran_check"]];
        _CheckTime = @[jsonElement[@"tran_hour"]];
        _CheckValue = @[check_total];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _Checknumbers.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

    static NSString *CellIdentifier = @"TableCell";

    TableCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    int row = [indexPath row];

    cell.CheckLabel.text = _Checknumbers[row];
    cell.CheckValue.text = _CheckValue[row];
    cell.CheckTime.text = _CheckTime[row];

    return cell;
}

@end

此代码检索您的数据并尊重双引号中的字段,以避免解析这些字段的内容。然而,似乎你还希望每个字符串检索一个双引号,所以你需要第二个循环来读取缺少的引号

string t = "\"test\",645,23.4,42,\"13,13,14\",\"test\"";
StringReader sr = new StringReader(t);
TextFieldParser tp = new TextFieldParser(sr);
tp.Delimiters = new string[] {","};
tp.HasFieldsEnclosedInQuotes = true;

string[] result = tp.ReadFields();

foreach(string s in result)
   Console.WriteLine(s);

顺便说一下,我不建议使用这个类,免费库或自定义代码。在这些选项之间进行选择总是在成本(写入,调试,测试,文档)和性能之间进行权衡。如果性能是解决方案的一个关键方面,那么您需要使用来自FTP服务器的真实数据来测试很多东西。只有您可以执行的任务。