how to create regular expression based on some condition

i want to create a regular expression to find and replace uppercase character based on some condition.

find the starting uppercase for a group of uppercase character in a string and replace it lowercase and * before the starting uppercase. If there is any lowercase following the uppercase,replace the uppercase with lowercase and * before the starting uppercase.

input string : stackOVERFlow

expected output : stack*over*flow

i tried but could not get it working perfectly.

Any idea on how to create a regular expression ? Thanks


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.

KeithS's solution can be simplified a bit


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


It will yield stack*over*flow

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

Need Your Help

How do I append a variable to another variable in JavaScript?

javascript loops append

I am running a loop, and I am trying to create a variable each time the loop runs with the number of the counter appended to the end of the variable name.

Find value assoaction in array

php arrays

i have a multi dimension array with sub array having repeated values of 'eduHisRowId' like:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.