Click here to Skip to main content
15,894,343 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

How should check a string has (?) at the end and rename to (?+1) using regex.

ie.

string text = "node (1)";

change to...

string text = "node (2)";

Thanks.
Posted
Comments
Maciej Los 13-Dec-13 5:09am    
Do you want to find ? or numeric value?

You can't do arithmetic with a regex. You can extract the current value with a regex (@"\((\d+)\)$"), do arithmetic on it in code and then replace the value:

str = str.Substring(0, str.LastIndexOf('(')) + newValue + ")";
 
Share this answer
 
Comments
Maciej Los 13-Dec-13 6:15am    
+5!
mbos015 13-Dec-13 14:17pm    
thanks your regex works sweet. starting to make sense of regex now. cheers.
just write if condition if char == ? then char == ?+ nothing else
 
Share this answer
 
Comments
Maciej Los 13-Dec-13 5:14am    
What?
As per i understand OP wants to find ? and replace it with numeric value. In your case, if you add char to char you'll get ? plus something else. Am i right?
Karthik_Mahalingam 13-Dec-13 5:24am    
Gaurav, OP needs solution in Regex.
Gaurav Makwana 13-Dec-13 23:24pm    
hey karthik i meant to say not write ?
just find syntax like that and dont need to use regex
fetch last character and check that character in if condition
Karthik_Mahalingam 13-Dec-13 23:50pm    
Ok cool :)
Hi Try this code..


C#
string text = "node (1)";
            string pattern = @"\(([^)]*)\)";
            if (Regex.IsMatch(text, pattern))
            {
                int newValue = 0;
                string oldValue= Regex.Match(text, pattern).Groups[1].Value;
                if (int.TryParse( oldValue, out newValue))
                    newValue++;
                text = text.Replace(oldValue, newValue.ToString());
            }
 
Share this answer
 
Comments
mbos015 13-Dec-13 14:16pm    
thanks worked well :), although the other suggestion using @"\((\d+)\)$")

works better, because the $ makes sure its at the end of the string.

what does ([^)]*) do?
BobJanova 16-Dec-13 5:00am    
This regex matches a left paren, then anything that isn't a right paren, then a right paren, and as you note it isn't tied to the end of the string. So for example in a string "CodeProject (UK) Ltd. (3)", this answer will match "UK" (and result in a string "CodeProject (0) Ltd. (3)") whereas mine will match "3".

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900