Reputation: 111
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.
Upvotes: 1
Views: 71
Reputation: 626748
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
Upvotes: 1