Reputation: 513
I have a string pattern, which contains a ID and Text to make markup easier for our staff.
The pattern to create a "fancy" button in our CMS is:
(button_section_ID:TEXT)
Example:
(button_section_25:This is a fancy button)
How do I extract the "This is a fancy button" part of that pattern? The pattern will always be the same. I tried to do some substring stuff but that got complicated very fast.
Any help would be much appreciated!
Upvotes: 2
Views: 2544
Reputation: 626802
If the text is always in the format you specified, you just need to trim parentheses and then split with :
:
var res = input.Trim('(', ')').Split(':')[1];
If the string is a substring, use a regex:
var match = Regex.Match(input, @"\(button_section_\d+:([^()]+)\)");
var res = match.Success ? match.Groups[1].Value : "";
See this regex demo.
Explanation:
\(button_section_
- a literal (button_section_
\d+
- 1 or more digits:
- a colon([^()]+)
- Group 1 capturing 1+ characters other than (
and )
(you may replace with ([^)]*)
to make matching safer and allow an empty string and (
inside this value)- a literal
)`Upvotes: 2
Reputation: 11840
The following .NET regex will give you a match containing a group with the text you want:
var match = Regex.Matches(input, @"\(button_section_..:(.*)\)");
The braces define a match group, which will give you everything between the button section, and the final curly brace.
Upvotes: 0