Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
938 views
in Technique[技术] by (71.8m points)

.net - Regular Expression Uppercase Replacement in C#

I have the following C# which simply replaces parts of the input string that look like EQUIP:19d005 into URLs, like this:

input = Regex.Replace(input, @"(EQUIP:)(S+)", @"<a title=""View equipment item $2"" href=""/EquipmentDisplay.asp?eqnum=$2"">$1$2</a>", RegexOptions.IgnoreCase);

The HTML ends up looking like this.

<a title="View equipment item 19d005" href="/EquipmentDisplay.asp?eqnum=19d005">EQUIP:19d005</a>

The only trouble is that the destination page expects the eqnum querystring to be all UPPERCASE so it returns the correct equipment when eqnum=19D005 but fails if it receives eqnum=19d005.

I guess I can modify and correct EquipmentDisplay.asp's errant requirement of uppercase values however, if possible I'd like to make the C# code comply with the existing classic ASP page by uppercasing the $2 in the Regex.Replace statement above.

Ideally, I'd like the HTML returned to look like this:

<a title="View equipment item 19d005" href="/EquipmentDisplay.asp?eqnum=19D005">EQUIP:19d005</a>

Notice although the original string was EQUIP:19d005 (lowercase), only the eqnum= value is uppercased.

Can it be done and if so, what's the tidiest way to do it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

OK, 2 solutions, one inline:

input = Regex.Replace(input, @"(EQUIP:)(S+)", m => string.Format(@"<a title=""View equipment item {1}"" href=""/EquipmentDisplay.asp?eqnum={2}"">{0}{1}</a>", m.Groups[1].Value, m.Groups[2].Value, m.Groups[2].Value.ToUpper()), RegexOptions.IgnoreCase);

The other using a separate function:

var input = Regex.Replace(input, @"(EQUIP:)(S+)", Evaluator, RegexOptions.IgnoreCase);

private static string Evaluator(Match match)
{
    return string.Format(@"<a title=""View equipment item {1}"" href=""/EquipmentDisplay.asp?eqnum={2}"">{0}{1}</a>", match.Groups[1].Value, match.Groups[2].Value, match.Groups[2].Value.ToUpper());
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...