0

我想创建一个正则表达式来根据某些条件查找和替换大写字符。

找到字符串中一组大写字符的起始大写,并将其替换为小写并*在起始大写之前。如果大写字母后面有小写字母,则将大写字母替换为小写字母,并*在开头的大写字母之前替换。

输入字符串stackOVERFlow

预期输出stack*over*flow

我试过但无法让它完美地工作。

关于如何创建正则表达式的任何想法?谢谢

4

2 回答 2

4

Well the expected inputs and outputs are slightly illogical: you're lower-casing the "f" in "flow" but not including it in the asterisk.

Anyway, the regex you want is pretty simple: @"[A-Z]+?". This matches a string of one or more uppercase alpha characters, nongreedily (don't think it makes a difference either way as the matched character class is relatively narrow).

Now, to do the find/replace, you would do something like the following:

Regex.Replace(inputString, @"([A-Z]+?)", "*$1*").ToLower();

This simply finds all occurrences of one or more uppercase alpha characters, and wherever it finds a match it replaces it with itself surrounded by asterisks. This does the surrounding but not the lowercasing; .NET Regex doesn't provide for that kind of string modification. However, since the end result of the operation should be a string with all lowercase chars, just do exactly that with a ToLower() and you'll get the expected result.

于 2012-05-02T20:29:02.260 回答
0

KeithS's solution can be simplified a bit

Regex.Replace("stackOVERFlow","[A-Z]+","*$0*").ToLower()

However, this will yield stack*overf*low including the f between the stars. If you want to exclude the last upper case letter, use the following expression

Regex.Replace("stackOVERFlow","[A-Z]+(?=[A-Z])","*$0*").ToLower()

It will yield stack*over*flow

This uses the pattern find(?=suffix), which finds a position before a suffix.

于 2012-05-02T20:55:56.220 回答