【.NET】字符串处理
类名:DealString
/// 1.截取字符串,最后加3个小数点
/// 2.获得指定Url的参数的string类型值
/// 3.判断数据类型
/// 4.过滤JS标记
/// 5.获取CheckBoxList属性值
/// 6.通过ID绑定CheckBoxList选项
/// 7.CheckBoxList取值
/// 8.设置CheckBoxList属性值
/// 9.通过ID绑定CheckBoxList选项
/// 10.得到按指定CheckBoxList选项字符串
/// 11.生成Execl
/// 12.获得当前绝对路径
/// 13.得到正则编译参数设置
/// 14.清除给定字符串中的回车及换行符
/// 15.分页方法
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions; namespace Tools
{
/// <summary>
/// DealString 的摘要说明。
/// </summary>
public class DealString
{ /// <summary>
/// 截取字符串
/// </summary>
/// <param name="obj"></param>
/// <param name="count"></param>
/// <returns></returns>
public static string substring(object obj, int count)
{
string str = tostring(obj);
if (str.Length > count)
{
str = obj.ToString().Substring(, count) + "...";
}
return str; } /// <summary>
/// 获得指定Url参数的string类型值
/// </summary>
/// <param name="strName">Url参数</param>
/// <param name="defValue">缺省值</param>
/// <returns>Url参数的string类型值</returns>
public static string GetQueryString(string strName)
{
string GetQueryString = (HttpContext.Current.Request.QueryString[strName]);
return GetQueryString;
} public static string tostring(object obj)
{
string result = "";
if (obj != null)
{
result = obj.ToString().Trim();
}
return result;
} /// <summary>
/// 过滤html标签
/// </summary>
/// <param name="TempStr"></param>
/// <returns></returns>
public static string StripHTML(string TempStr)
{
if (TempStr != null)
{
if (TempStr.Length > )
{
TempStr = regularExpressionsOfHTML(TempStr);
if (TempStr.Length > )
{
TempStr = TempStr.Substring(, TempStr.Length - );
}
}
TempStr = TempStr.Replace(" ", "");
}
return TempStr;
}
public static string regularExpressionsOfHTML(string TempContent)
{
//TempContent = System.Text.RegularExpressions.Regex.Replace(TempContent,"<[^>]+>",""); //任意多个
TempContent = System.Text.RegularExpressions.Regex.Replace(TempContent, "<[^>]*>", ""); //匹配一个
return TempContent.Trim(); }
/// <summary>
/// 判断数据类型
/// </summary>
/// <param name="strNumber)"></param>
/// <returns></returns>
public bool IsNumber(String strNumber)
{
Regex objNotNumberPattern = new Regex("[^0-9.-]");
Regex objTwoDotPattern = new Regex("[0-9]*[.][0-9]*[.][0-9]*");
Regex objTwoMinusPattern = new Regex("[0-9]*[-][0-9]*[-][0-9]*");
String strValidRealPattern = "^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$";
String strValidIntegerPattern = "^([-]|[0-9])[0-9]*$";
Regex objNumberPattern = new Regex("(" + strValidRealPattern + ")|(" + strValidIntegerPattern + ")"); return !objNotNumberPattern.IsMatch(strNumber) &&
!objTwoDotPattern.IsMatch(strNumber) &&
!objTwoMinusPattern.IsMatch(strNumber) &&
objNumberPattern.IsMatch(strNumber);
} public static bool IsNumeric(string value)
{
return Regex.IsMatch(value, @"^[+-]?\d*[.]?\d*$");
}
public static bool IsInt(string value)
{
return Regex.IsMatch(value, @"^[+-]?\d*$");
}
public static bool IsUnsign(string value)
{
return Regex.IsMatch(value, @"^\d*[.]?\d*$");
} /// <summary>
/// 过滤JS标记
/// </summary>
/// <param name="html"></param>
/// <returns></returns>
public string wipeScript(string html)
{
System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(@"<script[\s\S]+</script *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@" href *= *[\s\S]*script *:", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.Regex regex3 = new System.Text.RegularExpressions.Regex(@" on[\s\S]*=", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.Regex regex4 = new System.Text.RegularExpressions.Regex(@"<iframe[\s\S]+</iframe *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.Regex regex5 = new System.Text.RegularExpressions.Regex(@"<frameset[\s\S]+</frameset *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
html = regex1.Replace(html, ""); //过滤<script></script>标记
html = regex2.Replace(html, ""); //过滤href=javascript: (<A>) 属性
html = regex3.Replace(html, " _disibledevent="); //过滤其它控件的on...事件
html = regex4.Replace(html, ""); //过滤iframe
html = regex5.Replace(html, ""); //过滤frameset
return html;
} /// <summary>
/// 获取CheckBoxList属性值
/// </summary>
/// <param name="cbProperty">CheckBoxList对象</param>
/// <returns></returns>
public static string GetPropertyValue(CheckBoxList cbProperty)
{
string str_property = "";
for (int i = ; i < cbProperty.Items.Count; i++)
{
if (i != cbProperty.Items.Count - )
{
if (cbProperty.Items[i].Selected) str_property += "1,";
else str_property += "0,";
}
else
{
if (cbProperty.Items[i].Selected) str_property += "";
else str_property += "";
}
}
return str_property;
} /// <summary>
/// CheckBoxList取值
/// </summary>
/// <param name="Boxlist"></param>
/// <returns></returns>
public static string GetCheckBox(CheckBoxList Boxlist)
{
string chenkStr = "";
for (int i = ; i < Boxlist.Items.Count; i++)
{
if (Boxlist.Items[i].Selected == true)
{
chenkStr += Boxlist.Items[i].Value + ",";
}
}
return chenkStr;
} /// <summary>
/// 设置CheckBoxList属性值
/// </summary>
/// <param name="cbProperty">CheckBoxList对象</param>
/// <param name="propertyvalue">属性值</param>
public static void SetPropertyValue(CheckBoxList cbProperty, string propertyvalue)
{
string[] propertyArray = propertyvalue.Split(',');
for (int i = ; i < propertyArray.Length; i++)
{
if (propertyArray[i] == "") cbProperty.Items[i].Selected = true;
} }
/// <summary>
/// 通过ID绑定CheckBoxList选项
/// </summary>
/// <param name="cbList">CheckBoxList对象</param>
/// <param name="selectid">批定ID</param>
public static void SetSelectByID(CheckBoxList cbList, string selectid)
{
selectid = "," + selectid + ","; for (int i = ; i < cbList.Items.Count; i++)
{ if (selectid.IndexOf("," + cbList.Items[i].Value + ",") >= ) cbList.Items[i].Selected = true; }
}
/// <summary> /// 得到按指定CheckBoxList选项字符串
/// </summary>
/// <param name="cbList">CheckBoxList对象</param>
/// <returns></returns>
public static string GetSelectString(CheckBoxList cbList)
{
string result = "";
foreach (ListItem item in cbList.Items)
{
if (item.Selected) result += item.Value + ",";
}
return result.TrimEnd(new char[] { ',' });
} /// <summary>
/// 生成Execl
/// </summary>
/// <param name="dataset">要生成的数据</param>
/// <param name="typeid">1生成Execl、2直接把数据写入XML</param>
/// <param name="FileName">文件名</param>
/// <param name="page">当前页面类</param>
public static void CreateExcel(DataSet dataset, int typeid, string FileName, System.Web.UI.Page page)
{
HttpResponse resp;
resp = page.Response;
resp.ContentEncoding = System.Text.Encoding.GetEncoding();
resp.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(FileName));
string colHeaders = "", ls_item = "";
int i = ; //定义表对象与行对像,同时用DataSet对其值进行初始化
DataTable datatable = dataset.Tables[];
DataRow[] myRow = datatable.Select("");
// typeid=="1"时导出为EXCEL格式文件;typeid=="2"时导出为XML格式文件
if (typeid == )
{
//取得数据表各列标题,各标题之间以\t分割,最后一个列标题后加回车符
for (i = ; i < datatable.Columns.Count - ; i++)
colHeaders += datatable.Columns[i].Caption.ToString() + "\t";
colHeaders += datatable.Columns[i].Caption.ToString() + "\n";
//向HTTP输出流中写入取得的数据信息
resp.Write(colHeaders);
//逐行处理数据
foreach (DataRow row in myRow)
{
//在当前行中,逐列获得数据,数据之间以\t分割,结束时加回车符\n
for (i = ; i < row.ItemArray.Length - ; i++)
ls_item += row[i].ToString() + "\t";
ls_item += row[i].ToString() + "\n";
//当前行数据写入HTTP输出流,并且置空ls_item以便下行数据
resp.Write(ls_item);
ls_item = "";
}
}
else
{
if (typeid == )
{
//从DataSet中直接导出XML数据并且写到HTTP输出流中
resp.Write(dataset.GetXml());
}
}
//写缓冲区中的数据到HTTP头文件中
resp.End();
} /// <summary>
/// 获得当前绝对路径
/// </summary>
/// <param name="strPath">指定的路径</param>
/// <returns>绝对路径</returns>
public static string GetMapPath(string strPath)
{
if (HttpContext.Current != null)
{
return HttpContext.Current.Server.MapPath(strPath);
}
else //非web程序引用
{
strPath = strPath.Replace("/", "\\");
if (strPath.StartsWith("\\"))
{
strPath = strPath.Substring(strPath.IndexOf('\\', )).TrimStart('\\');
}
return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
}
} /// <summary>
/// 得到正则编译参数设置
/// </summary>
/// <returns>参数设置</returns>
public static RegexOptions GetRegexCompiledOptions()
{
#if NET1
return RegexOptions.Compiled;
#else
return RegexOptions.None;
#endif
} /// <summary>
/// 清除给定字符串中的回车及换行符
/// </summary>
/// <param name="str">要清除的字符串</param>
/// <returns>清除后返回的字符串</returns> private static Regex RegexBr = new Regex(@"(\r\n)", RegexOptions.IgnoreCase);
public static Regex RegexFont = new Regex(@"<font color=" + "\".*?\"" + @">([\s\S]+?)</font>", GetRegexCompiledOptions());
public static string ClearBR(string str)
{
Match m = null; for (m = RegexBr.Match(str); m.Success; m = m.NextMatch())
{
str = str.Replace(m.Groups[].ToString(), "");
} return str;
} }
}
【.NET】字符串处理的更多相关文章
- Python高手之路【六】python基础之字符串格式化
Python的字符串格式化有两种方式: 百分号方式.format方式 百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存.[PEP-3101] This ...
- 测试一下StringBuffer和StringBuilder及字面常量拼接三种字符串的效率
之前一篇里写过字符串常用类的三种方式<java中的字符串相关知识整理>,只不过这个只是分析并不知道他们之间会有多大的区别,或者所谓的StringBuffer能提升多少拼接效率呢?为此写个简 ...
- java中的字符串相关知识整理
字符串为什么这么重要 写了多年java的开发应该对String不陌生,但是我却越发觉得它陌生.每学一门编程语言就会与字符串这个关键词打不少交道.看来它真的很重要. 字符串就是一系列的字符组合的串,如果 ...
- JavaScript 字符串实用常操纪要
JavaScript 字符串用于存储和处理文本.因此在编写 JS 代码之时她总如影随形,在你处理用户的输入数据的时候,在读取或设置 DOM 对象的属性时,在操作 Cookie 时,在转换各种不同 Da ...
- Java 字符串格式化详解
Java 字符串格式化详解 版权声明:本文为博主原创文章,未经博主允许不得转载. 微博:厉圣杰 文中如有纰漏,欢迎大家留言指出. 在 Java 的 String 类中,可以使用 format() 方法 ...
- Redis的简单动态字符串实现
Redis 没有直接使用 C 语言传统的字符串表示(以空字符结尾的字符数组,以下简称 C 字符串), 而是自己构建了一种名为简单动态字符串(simple dynamic string,sds)的抽象类 ...
- ASP.NET加密和解密数据库连接字符串
大家知道,在应用程序中进行数据库操作需要连接字符串,而如果没有连接字符串,我们就无法在应用程序中完成检索数据,创建数据等一系列的数据库操作.当有人想要获取你程序中的数据库信息,他首先看到的可能会是We ...
- Javascript正则对象方法与字符串正则方法总结
正则对象 var reg = new Regexp('abc','gi') var reg = /abc/ig 正则方法 test方法(测试某个字符串是否匹配) var str = 'abc123'; ...
- 微信小程序中利用时间选择器和js无计算实现定时器(将字符串或秒数转换成倒计时)
转载注明出处 改成了一个单独的js文件,并修改代码增加了通用性,点击这里查看 今天写小程序,有一个需求就是用户选择时间,然后我这边就要开始倒计时. 因为小程序的限制,所以直接选用时间选择器作为选择定时 ...
- ThinkPHP+Smarty模板中截取包含中英文混合的字符串乱码的解决方案
好几天没写博客了,其实有好多需要总结的,因为最近一直在忙着做项目,但是困惑了几天的Smarty模板中截取包含中英文混合的字符串乱码的问题,终于解决了,所以记录下来,需要的朋友看一下: 出现乱码的原因: ...
随机推荐
- yum局域网软件源搭建
之前的Demo算是告一段落了,期末的各种考试报告也结束了. 暑假的一项任务就是和其他几个同学一起,在若干台服务器上安装openstack,虚拟出更多的机器,对各种分布式/并行数据分析平台进行测试. 目 ...
- JVM参数设置、分析
不管是YGC还是Full GC,GC过程中都会对导致程序运行中中断,正确的选择不同的GC策略,调整JVM.GC的参数,可以极大的减少由于GC工作,而导致的程序运行中断方面的问题,进而适当的提高Java ...
- NUTZ中处理系统未捕获异常
关键内容 mvc-chain.js ViewProcessor ai.setFailView(“redirect:/sysError.html”); log.error(this.trrowableT ...
- Python中Generators教程
转载至:https://www.bytelang.com/article/content/NQbmUaRIXyA= 要想创建一个iterator,必须实现一个有__iter__()和__next__( ...
- CSS3特性修改(自定义)浏览器默认滚动条
前言:我们做前端时,会遇到一些需求,要求把默认浏览器的滚动条样式给改写了,诶.好好的改它干啥了,也带不来用户体验,就是好看点嘛!实现原理其实是用了伪元素,webkit的伪元素实现很强,可以把滚动条当成 ...
- 动态SQL语句:定义(一)
文章系列 动态SQL语句:定义(一) 静态SQL与动态SQL 静态SQL:程序运行前,具有固定的形式和结构的SQL. 动态SQL:程序运行时,能够动态改变形式或结构的SQL. 一些思考和想法 在实际的 ...
- 搭建PHP建站环境
PHP是一种网站后端脚本语言,通常在web开发中使用apache+PHP+MYSQL这种黄金搭档来建立支持PHP的站点,PHP运行环境或者说任何技术的运行环境都不是简单的加法,即使是安装有apache ...
- [bzoj2957][楼房重建] (线段树)
Description 小A的楼房外有一大片施工工地,工地上有N栋待建的楼房.每天,这片工地上的房子拆了又建.建了又拆.他经常无聊地看着窗外发呆,数自己能够看到多少栋房子. 为了简化问题,我们考虑这些 ...
- Java多线程基础——线程间通信
在使用多线程的时候,经常需要多个线程进行协作来完成一件事情.在前面两章分析了Java多线程的基本使用以及利用synchronized来实现多个线程同步调用方法或者执行代码块.但上面两章的内容涉及到的例 ...
- Redmine管理项目1-自定义属性
先是点击页面导航条(最上面那排菜单,有主页.我的工作台.项目.管理.帮助等)上的“管理”菜单,看到下图: 看到里面的“自定义属性”菜单了吧,点击它,可以看到下面的界面: 点击那个“新建自定义属性”菜单 ...