文字添加or删除前后缀,正则表达式内容替换工具
本帖最后由 fangmin723 于 2024-1-28 14:35 编辑文字处理代码(关键代码,非全部):
/// <summary>
/// 文字添加或删除前后缀
/// </summary>
/// <param name="isadd">添加前后缀还是删除前后缀</param>
/// <param name="ispre">是否添加前缀</param>
/// <param name="prefix">前缀</param>
/// <param name="issuf">是否添加后缀</param>
/// <param name="suffix">后缀</param>
public static void Tools_AddOrDelFix(bool isadd, bool ispre, string prefix, bool issuf, string suffix)
{
var objids = Tools_GetTextEntity();
if (!objids.Any()) return;
var Db = HostApplicationServices.WorkingDatabase;
var Doc = Acap.DocumentManager.MdiActiveDocument;
var Ed = Doc.Editor;
using var dloc = Doc.LockDocument();
using var tr = Db.TransactionManager.StartTransaction();
objids.ForEach(id =>
{
var entity = tr.GetObject(id, OpenMode.ForWrite) as Entity;
if (isadd)
{
if (entity is DBText text)
text.TextString = $"{(ispre ? prefix : "")}{text.TextString}{(issuf ? suffix : "")}";
if (entity is MText mText)
mText.Contents = $"{(ispre ? prefix : "")}{mText.Contents}{(issuf ? suffix : "")}";
}
else
{
if (entity is DBText text)
{
if (ispre)
text.TextString = text.TextString.TrimStart(prefix.ToCharArray());
if (issuf)
text.TextString = text.TextString.TrimEnd(suffix.ToCharArray());
}
if (entity is MText mText)
{
if (ispre)
mText.Contents = mText.Contents.TrimStart(prefix.ToCharArray());
if (issuf)
mText.Contents = mText.Contents.TrimEnd(suffix.ToCharArray());
}
}
});
tr.Commit();
}
/// <summary>
/// 文字内容替换
/// </summary>
/// <param name="regstr">正则表达式或者字符串</param>
/// <param name="newstr">替换内容</param>
/// <param name="iscase">是否区分大小写,默认 :false不区分</param>
/// <param name="isall">是否全字匹配,默认:false不全字匹配</param>
public static void Tools_ReplacePattern(string regstr, string newstr, bool iscase = false, bool isall = false)
{
var objids = Tools_GetTextEntity();
if (!objids.Any()) return;
if (isall) regstr = $"^{regstr}$";
var Db = HostApplicationServices.WorkingDatabase;
var Doc = Acap.DocumentManager.MdiActiveDocument;
var Ed = Doc.Editor;
using var dloc = Doc.LockDocument();
using var tr = Db.TransactionManager.StartTransaction();
objids.ForEach(id =>
{
var entity = tr.GetObject(id, OpenMode.ForWrite) as Entity;
if (entity is DBText text)
{
text.TextString = iscase
? Regex.Replace(text.TextString, regstr, newstr)
: Regex.Replace(text.TextString, regstr, newstr, RegexOptions.IgnoreCase);
}
if (entity is MText mText)
mText.Contents = iscase
? Regex.Replace(mText.Contents, regstr, newstr)
: Regex.Replace(mText.Contents, regstr, newstr, RegexOptions.IgnoreCase);
});
tr.Commit();
}
2024.1.28:增加异常处理
https://www.bilibili.com/video/BV1ek4y1Z76k/
是不是发错地方了。。 不好意思,是我看错了。。:lol 谢谢分享原创工具
仅ZWcad用嘛? lxl217114 发表于 2024-1-25 17:07
谢谢分享原创工具
仅ZWcad用嘛?
附件是仅zwcad使用的,我没有autocad,所以暂时没有发布AutoCAD的dll
页:
[1]