【发布时间】:2020-09-09 05:06:23
【问题描述】:
我需要过滤字符串中特定单词后的数字。例如
(CaseId : 200908005485) 测试 WTest3 ==> 需要编号200908005485
[CaseId : 200908005486] 测试 WTest ==> 需要编号 200908005486
注意:CaseId 可以在字符串中的任何位置。
private string GetObjectIDFromSubjectWithCustomExpression(ItemType itemType, string subject, string expression)
{
if (string.IsNullOrEmpty(expression))
return null;
//[Case ID:678878], [Case ID:#ObjectId#]
string exp = GetFieldNameFromExpression(expression);
var pattern = expression.Replace("#" + exp + "#", "[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]");
if (subject.Contains('('))
{
pattern = expression.Replace("[", "(").Replace("]", ")").Replace("#" + exp + "#", "[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]");
pattern = pattern.TrimEnd();
}
var rx = new Regex(pattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
if (rx.IsMatch(subject))
{
var collection = rx.Matches(subject);
if (collection.Count > 0)
{
var matchedstring = collection[collection.Count - 1].Value;
Regex re = new Regex(@"\d+");
Match m = re.Match(matchedstring);
if (m.Success && !string.IsNullOrEmpty(m.Value))
{
exp = m.Value;
return exp;
}
}
}
return null;
}
试过了,效果很好,但我想要一种更有效的方法。
【问题讨论】:
-
用
:作为分隔符分割字符串怎么样,比如expression.Split(":")[1] -
请定义“更高效”?在什么方面有效?
-
@FranzGleichmann 高效,它可以是 6 位数字或 13 位数字。它可能会有所不同。
-
@that_guy_jrb 这绝不是效率,而是增加功能的特定方式。
-
另外,this page of the manual 可能会回答你的问题