简体   繁体   English

C#格式字符串,我可以从中获取不同的值

[英]C# Format string in a way I can get different values from it

What is the best way to format the below string in a way so that I can separate out and find the value of PractitionerId, PhysicianNPI, PhysicianName etc. 格式化下面的字符串的最佳方法是什么,以便我可以分离出并找到PractitionerId,PhysicianNPI,PhysicianName等的值。

"PractitionerId:4343343434 , PhysicianNPI: 43434343434, PhysicianName: John, Doe, PhysicianPhone:2222222222 , PhysicianFax:3333333333 " “ PractitionerId:4343343434,医师NPI:43434343434,医师名称:John,Doe,医师电话:2222222222,医师传真:3333333333”

So finally I want something like this: 所以最后我想要这样的东西:

var practitionerId = "4343343434 ";
var physNPI = "43434343434";
 var phyName = "John, Doe";

I was thinking of splitting with the names and finding the values assigned to each field but I am not sure if that is the best solution to it. 我当时正在考虑拆分名称,并找到分配给每个字段的值,但是我不确定这是否是最好的解决方案。

You could probably generalise this with a regular expression, then use it to build a dictionary/lookup of the terms. 您可能可以使用正则表达式对此进行概括,然后使用它来构建术语的字典/查找。

So: 所以:

var input= "PractitionerId:4343343434 , PhysicianNPI: 43434343434,"
           + " PhysicianName: John, Doe, PhysicianPhone:2222222222 ,"
           + " PhysicianFax:3333333333";

var pattern = @"(?<=(?<n>\w+)\:)\s*(?<v>.*?)\s*((,\s*\w+\:)|$)";
var dic = Regex
              .Matches(input, pattern)
              .Cast<Match>()
              .ToDictionary(m => m.Groups["n"].Value, 
                            m => m.Groups["v"].Value);

So now you can: 现在,您可以:

var practitionerId = dic["PractitionerId"];

or 要么

var physicianName = dic["PhysicianName"];

You could get the exact information, doing something like: 您可以通过以下方式获取确切信息:

var str = "PractitionerId:4343343434 , PhysicianNPI: 43434343434, PhysicianName: John, Doe, PhysicianPhone:2222222222 , PhysicianFax:3333333333 ";

var newStr = str.Split(','); 

var practitionerID = newStr[0].Split(':')[1]; // "4343343434"
var physicianNPI = newStr[1].Split(':')[1].Trim(); // "43434343434"
var phyName = newStr[2].Split(':')[1].Trim() + "," + newStr[3]; // "John, Doe"

There are cleaner solutions using Regex patterns though. 有一些使用Regex模式的更干净的解决方案。

Also, you need to parse the corresponding variables to the specific data type you want. 另外,您需要将相应的变量parse为所需的特定数据类型。 Everything here is being treated as a string 这里的一切都被当作string

Since you seperate information with ",", this should work: 由于您用“,”分隔信息,因此应该可以:

   string[] information = yourWholeString.Split(",");
   string practitionerId = information[0];
   string physNPI = information[1];
   string phyName = information[2] + information[3];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM