Hercules
Hercules

Reputation: 45

Regular Expression to match from specified character to second line end

i have text like this

aaa111
bbb222
ccc333
ddd444

and i need to match with Regular Expression from specified character to second new line
for example from bbb return like this :

ccc333

i used this code but not work fine

            string[] lines = input.Split('\n');
            string nums = "";
            for (int i = 1; i < 10; i++)
            {
                nums = lines.Length >= i ? lines[i - 1] : null;
                Match match = Regex.Match(nums, @"\bbbb\w*\b");
                if (match.Success)
                {
                    break;
                }
            }

Upvotes: 1

Views: 142

Answers (2)

anubhava
anubhava

Reputation: 784958

Submitting my comment to answer so that solution is easy to find for future visitors.

You may use this regex:

\bbbb.*\r?\n(.*)

RegEx Demo

RegEx Breakup:

  • \b: Word boundary
  • bbb: Match bbb
  • .*\r?\n(.*): Match any text followed by a line break followed by any text with 0 or more length. We capture last (.*) in group #1

Code:

string pattern = @"\bbbb.*\r?\n(.*)";
string input = @"aaa111
bbb222
ccc333
ddd444";
        
foreach (Match m in Regex.Matches(input, pattern)) {
   Console.WriteLine(m.Groups[1]); // ccc333
}

Online Code Demo

Upvotes: 1

EagleBirdman
EagleBirdman

Reputation: 182

If your data is well constrained, you can use

^bbb\d{3}\s\w{3}\d{3}$

An explanation

Upvotes: 1

Related Questions