using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace JiepeiWMS.Common.Helper { public class StringHelper { /// /// 根据分隔符返回前n条数据 /// /// 数据内容 /// 分隔符 /// 前n条 /// 是否倒序(默认false) /// public static List GetTopDataBySeparator(string content, string separator, int top, bool isDesc = false) { if (string.IsNullOrEmpty(content)) { return new List() { }; } if (string.IsNullOrEmpty(separator)) { throw new ArgumentException("message", nameof(separator)); } var dataArray = content.Split(separator).Where(d => !string.IsNullOrEmpty(d)).ToArray(); if (isDesc) { Array.Reverse(dataArray); } if (top > 0) { dataArray = dataArray.Take(top).ToArray(); } return dataArray.ToList(); } /// /// 获取字符串中的数字 /// /// 字符串 /// 数字 public static decimal GetNumber(string str) { decimal result = 0; if (str != null && str != string.Empty) { // 正则表达式剔除非数字字符(不包含小数点.) //str = Regex.Replace(str, @"[^/d./d]", ""); str = Regex.Replace(str, @"[^\d.\d]", ""); // 如果是数字,则转换为decimal类型 if (Regex.IsMatch(str, @"^[+-]?\d*[.]?\d*$")) { result = decimal.Parse(str); } } return result; } /// /// 获取字符串中的数字 /// /// 字符串 /// 数字 public static decimal GetNumberInt(string str) { decimal result = 0; if (str != null && str != string.Empty) { // 正则表达式剔除非数字字符(不包含小数点.) str = Regex.Replace(str, @"[^\d.\d]", ""); // 如果是数字,则转换为decimal类型 if (Regex.IsMatch(str, @"^[+-]?\d*[.]?\d*$")) { result = int.Parse(str); } } return result; } } }