且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从字符串中拆分int和其他字符

更新时间:2023-02-21 14:47:23

正则表达式似乎是你需要的:

A regular expression seems to be what you need here:
using System.Text.RegularExpressions;

Regex regex = new Regex(@"^(?<Quantity>[0-9]+)(?<Unit>[^0-9]+)


,RegexOptions .Compiled | RegexOptions.CultureInvariant);

string input = 12颗跨度>;
匹配m = regex.Match(输入);
int quantity = int .Parse(m.Groups [ Quantity]。Value);
string unit = m.Groups [ 单元跨度>]值。

// quantity = 12
// unit =pcs
", RegexOptions.Compiled | RegexOptions.CultureInvariant); string input = "12pcs"; Match m = regex.Match(input); int quantity = int.Parse(m.Groups["Quantity"].Value); string unit = m.Groups["Unit"].Value; // quantity = 12 // unit = "pcs"



希望这有帮助。


Hope this helps.


另一种方法是使用 Linq [ ^ ] + Regex.Replace方法 [ ^ ]。



想象一下,您确实将数据加载到DataTable对象中,因此您可以将数量数据拆分为数量 (字符串)和单位(int):

Another way is to use Linq[^] + Regex.Replace method[^].

Imagine, you did load the data into DataTable object, so you're able to split quantity data into quantity(string) and unit(int):
DataTable dt  = new DataTable();
dt.Columns.Add(new DataColumn("id", typeof(int)));
dt.Columns.Add(new DataColumn("product_price", typeof(int)));
dt.Columns.Add(new DataColumn("quantity", typeof(string)));
dt.Rows.Add(new Object[]{1, 500, "1Kg"});
dt.Rows.Add(new Object[]{2, 250, "500gm"});
dt.Rows.Add(new Object[]{3, 100, "12pcs"});
dt.Rows.Add(new Object[]{4, 150, "12nos"});

string patternq = @"\d+";
string patternu = @"\B[A-Z]+";

var result = dt.AsEnumerable()
    .Select(x=>new
    {
        id = x.Field<int>("id"),
        price = x.Field<int>("product_price"),
        quantity = Convert.ToInt32(Regex.Replace(x.Field<string>("quantity"), patternu, string.Empty ,System.Text.RegularExpressions.RegexOptions.IgnoreCase)),
        unit = Regex.Replace(x.Field<string>("quantity"), patternq, string.Empty, System.Text.RegularExpressions.RegexOptions.None)
    }).ToList();

foreach(var obj in result)
{
    Console.WriteLine("{0}\t{1}\t{2}\t{3}", obj.id, obj.price, obj.quantity, obj.unit);
}