-4

I want to split above string using regex in c#

Input :

"some1 Text (#something) someothertext (#something) some3 Text"

Expected Output:

some1 Text
someothertext
some3 Text

My Code

string str = "some1 Text (#something) someothertext (#something) some3 Text";
Regex regex = new Regex(@"\(([^)]*)\)", RegexOptions.IgnoreCase);
var result = regex.Split(str);

Output

some1 Text
#something
someothertext
#something
some3 Text
Maximilian Ast
  • 3,369
  • 12
  • 36
  • 47

2 Answers2

1
String input = "some1 Text (#One) some2 other (#something) some3 Text";
String pattern = @"\(#.*?\)";
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(pattern);
string output = regex.Replace(input, System.Environment.NewLine);

Breakdown of regex: \(#.*?\)

  • Escaped Left Parenthesis: \\(
  • Pound symbol: #
  • Match anything for any number of characters: .*
  • Non-Greedy Operator: ?
  • Escaped Right Parenthesis: \\)
0

You can match both the separators and the fields with (?<field>[^\(]+)(?<delim>\(#[^\)]*\))?. You can refer to each part by name, eg field or delim. For example:

var input = "some1 Text (#One) some2 other (#something) some3 Text";
var pattern = @"(?<field>[^\(]+)(?<delim>\(#[^\)]*\))??";

var matches = Regex.Matches(input,pattern);
var fields=from match in matches.OfType<Match>()
           select match.Group["field"].Value;
foreach(var field in fields)
{
    Console.WriteLine(field);
}

Results:

some1 Text  
 some2 other  
 some3 Text 

The expression captures everything that isn't a ( as the field. Anything between (# and)` is captured as the delimiter.

Captured doesn't mean that a string is generated. The loop only retrieves the values of the fields

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236