1

I have a requirement to find a text pattern [anystring].[anystring] with in a larger text.

I wrote a regex code to achieve this

var pattern = @"\[(.*?)\]\.\[(.*?)\]";
string CustomText = "some text here [anystring].[anystring] some text here etc"
var matchesfound = System.Text.RegularExpressions.Regex.Matches(CustomText, pattern);

This code works fine and detects the "[string].[string]" pattern but it fails for this

var pattern = @"\[(.*?)\]\.\[(.*?)\]";
string CustomText = "[somestring]=[anystring].[anystring]"
var matchesfound = System.Text.RegularExpressions.Regex.Matches(CustomText, pattern)

In the above scenario, it identifies the whole string "[somestring]=[anystring].[anystring]" but I want only "[anystring].[anystring]" to be identified as match. Any help with this please? Thank you.

1
  • Use \[([^][]*)\]\.\[([^][]*)\] Commented Jul 4, 2021 at 18:42

1 Answer 1

1

You can use

\[([^][]*)]\.\[([^][]*)]

See the regex demo. Details:

  • \[ - a [ char
  • ([^][]*) - Group 1: any zero or more chars other than [ and ]
  • ]\.\[ - ].[ substring
  • ([^][]*) - Group 2: any zero or more chars other than [ and ]
  • ] - a ] char.

See the C# demo:

var pattern = @"\[([^][]*)]\.\[([^][]*)]";
var CustomText = "[somestring]=[anystring].[anystring]";
var matchesfound = System.Text.RegularExpressions.Regex.Matches(CustomText, pattern);
foreach (Match m in matchesfound) 
{
    Console.WriteLine($"Group 1: {m.Groups[1].Value}\nGroup 2: {m.Groups[2].Value}");
}

Output:

Group 1: anystring
Group 2: anystring
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.