Regex matching group - c#

I have the following pattern format of text:
[1/#DaysInMonth #FirstTitle] #SecondTitle
The #DaysInMonth is gets on how many days are there based on the selected month, #FirstTitle and the #SecondTitle is alphanumeric.
I tried with the following:
[\1(?<DaysInMonth>\d\s+) (?<FirstTitle>[\w\s \]+)\] (?<SecondTitle>[\w\s \]+)$]
But it didn't seems to working. The matches character is 53 characters. [Link]
How can I solve this?
Edit after #baddger964 answer:
I want to use in my application like this:
private Regex _regex = null;
string value = "[1/30 Development In Progress] Development In Progress";
_regex = new Regex(#"\[\d+\/(?<DaysInMonth>\d+)\s(?<FirstTitle>[\w\s]+)\]\s(?<SecondTitle>[\w\s]+)").Match(value);
string value1 = _regex.Groups["DaysInMonth"].Value;
string value2 = _regex.Groups["FirstTitle"].Value;
string value3 = _regex.Groups["SecondTitle"].Value;
Your answer much appreciated.
Thank you.

Maybe you can use this :
\[\d+\/(?<DaysInMonth>\d+)\s(?<FirstTitle>[\w\s]+)\]\s(?<SecondTitle>[\w\s]+)
for note :
\1 => dont escape the "1" because \1 match the same thing as the last defined match group.
[ => ou have to escape this \[ because with [ you create a set of caracters
so your regex :
[\1(?<DaysInMonth>\d\s+) (?<FirstTitle>[\w\s \]+)\] (?<SecondTitle>[\w\s \]+)$]
says : i want match one caracter from this set of caracter :
\1(?<DaysInMonth>\d\s+) (?<FirstTitle>[\w\s \]+)\] (?<SecondTitle>[\w\s \]+)$

Like this?
Here is an example of a normal regex if you interesse.
https://regex101.com/r/wLBj7Z/1

Related

Regular expression match between string and last digit

I'm trying to come up with a regular expression matches the text in bold in all the examples.
Between the string "JZ" and any character before "-"
JZ123456789-301A
JZ134255872-22013
Between the string "JZ" and the last character
JZ123456789D
I have tried the following but it only works for the first example
(?<=JZ).*(?=-)
You can use (?<=JZ)[0-9]+, presuming the desired text will always be numeric.
Try it out here
You may use
JZ([^-]*)(?:-|.$)
and grab Group 1 value. See the regex demo.
Details
JZ - a literal substring
([^-]*) - Capturing group 1: zero or more chars other than -
(?:-|.$) - a non-capturing group matching either - or any char at the end of the string
C# code:
var m = Regex.Match(s, #"JZ([^-]*)(?:-|.$)");
if (m.Success)
{
Console.WriteLine(m.Groups[1].Value);
}
If, for some reason, you need to obtain the required value as a whole match, use lookarounds:
(?<=JZ)[^-]*(?=-|.$)
See this regex variation demo. Use m.Value in the code above to grab the value.
A one-line answer without regex:
string s,r;
// if your string always starts with JZ
s = "JZ123456789-301A";
r = string.Concat(s.Substring(2).TakeWhile(char.IsDigit));
Console.WriteLine(r); // output : 123456789
// if your string starts with anything
s = "A12JZ123456789-301A";
r = string.Concat(s.Substring(s.IndexOf("JZ")).TakeWhile(char.IsDigit));
Console.WriteLine(r); // output : 123456789
Basically, we remove everything before and including the delimiter "JZ", then we take each char while they are digit. The Concat is use to transform the IEnumerable<char> to a string. I think it is easier to read.
Try it online

Regex pattern generator

I'm trying to do regex pattern which will match to this:
Name[0]/Something
or
Name/Something
Verbs Name and Something will be always known.
I did for Name[0]/Something, but I want make pattern for this verb in one regex
I've tried to sign [0] as optional but it didn't work :
var regexPattern = "Name" + #"\([\d*\]?)/" + "Something"
Do you know some generator where I will input some verbs and it will make pattern for me?
Use this:
Name(\[\d+\])?\/Something
\d+ allows one or more digits
\[\d+\] allows one or more digits inside [ and ]. So it will allow [0], [12] etc but reject []
(\[\d+\])? allows digit with brackets to be present either zero times or once
\/ indicates a slash (only one)
Name and Something are string literals
Regex 101 Demo
You were close, the regex Name(\[\d+\])?\/Something will do.
The problem is with first '\' in your pattern before '('.
Here is what you need:
var str = "Name[0]/Something or Name/Something";
Regex rg = new Regex(#"Name(\[\d+\])?/Something");
var matches = rg.Matches(str);
foreach(Match a in matches)
{
Console.WriteLine(a.Value);
}
var string = 'Name[0]/Something';
var regex = /^(Name)(\[\d*\])?\/Something$/;
console.log(regex.test(string));
string = 'Name/Something';
console.log(regex.test(string));
You've tried wrong with this pattern: \([\d*\]?)/
No need to use \ before ( (in this case)
? after ] mean: character ] zero or one time
So, if you want the pattern [...] displays zero or one time, you can try: (\[\d*\])?
Hope this helps!
i think this is what you are looking for:
Name(\[\d+\])?\/Something
Name litteral
([\d+])? a number (1 or more digits) between brackets optional 1 or 0 times
/Something Something litteral
https://regex101.com/r/G8tIHC/1

Regex to replace between starting curly bracket { and colon :

I wanted to replace a part of string between curly bracket and colon. Suppose I have a string like :
{Name: {\"before\":'Aj', \"after\":'Ajay'} },
So now I want to replace the part of string {Name: with {"Name":.
I tried doing Regex.Replace(rectifyAfter, #"/{([^\s].+?)(\s|$):", "{\"$1\":"). But it doesn't do the replace.
Can anyone please help me with it?
The following regex should do the trick:
(?:\{)(?<Property>[a-z0-9]+)(?:\:)
What it does:
(?:\{) - matches but doesn't capture the opening curly bracket
(?<Property>[a-z0-9]+) - captures the name of the property in a capturing group named Property
(?:\:) - again, matches but doesn't capture the : after the property
So, basically, what you want to do is match the pattern {Name: but have it replaced with {" + value of Property group + :.
And below is the code to do the replacement:
string pattern = #"(?:\{)(?<Property>[a-z0-9]+)(?:\:)";
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
string targetString = #"{Name: {\""before\"":'Aj', \""after\"":'Ajay'} },";
string replacement = #"{""${Property}"":";
return regex.Replace(targetString, replacement);
${Property} is the name of the capturing group and it will hold the name of your property.
I don't see why you'd need regex for this. Just use a simple .Replace
string json = "" //Whatever your JSON string is.
json = json.Replace("{Name:", "{\"Name\":");

Need pattern for a complex Regex Split

I'd like to split the following string
// Comments
KeyA : SomeType { SubKey : SubValue } KeyB:'This\'s a string'
KeyC : [ 1 2 3 ] // array value
into
KeyA
:
SomeType
{ SubKey : SubValue }
KeyB
:
This's a string
KeyC
:
[ 1 2 3 ]
(: and blank spaces are the delimiters although : is kept in the result; comments are ignored; no splitting between {}, [], or '')
Can I achieve that with Regex Split or Match? If so, what would be the right pattern? Comments to the pattern string would be appreciated.
Moreover, it's also desirable to throw exception or return an error message if the input string is not valid (see the comment below).
Thanks.
You can use this pattern...
string pattern = #"(\w+)\s*:\s*((?>[^\w\s\"'{[:]+|\w+\b(?!\s*:)|\s(?!\w+\s*:|$)|\[[^]]*]|{[^}]*}|\"(?>[^\"\\]|\\.)*\"|'(?>[^'\\]|\\.)*')+)\s*";
... in two ways:
with Match method which will give you what you are looking for with keys in group 1 and values in group 2
with Split method, but you must remove all the empty results.
How is build the second part (after the :) of the pattern?
The idea is to avoid, first at all, problematic characters: [^\w\s\"'{[:]+
Then you allow each of these characters but in a specific situation:
\w+\b(?!\s*:) a word that is not the key
\s(?!\w+\s*:|$) spaces that are not at the end of the value (to trim them)
\[[^]]*] content surrounded by square brackets
{[^}]*} the same with curly brackets
"(?>[^"\\]|\\\\|\\.)*" content between double quotes (with escaped double quotes allowed)
'(?>[^'\\]|\\\\|\\.)*' the same with single quotes
Note that the problem with colon inside brackets or quotes is avoided.
I'm not quite sure what you're looking for when you get to KeyC. How do you know when the string value for KeyB ends and the string for KeyC begins? Is there a colon after 'this\'s is a string' or a line break? Here's a sample to get you started:
[TestMethod]
public void SplitString()
{
string splitMe = "KeyA : SubComponent { SubKey : SubValue } KeyB:This's is a string";
string pattern = "^(.*):(.*)({.*})(.*):(.*)";
Match match = Regex.Match(splitMe, pattern);
Assert.IsTrue(match.Success);
Assert.AreEqual(6, match.Groups.Count); // 1st group is the entire match
Assert.AreEqual("KeyA", match.Groups[1].Value.Trim());
Assert.AreEqual("SubComponent", match.Groups[2].Value.Trim());
Assert.AreEqual("{ SubKey : SubValue }", match.Groups[3].Value.Trim());
Assert.AreEqual("KeyB", match.Groups[4].Value.Trim());
Assert.AreEqual("This's is a string", match.Groups[5].Value.Trim());
}
this Regex pattern should work for you
\s*:\s*(?![^\[]*\])(?![^{]*})(?=(([^"]*"[^"]*){2})*$|[^"]+$)
when replaced with
\n$0\n
Demo

Problem creating regex to match filename

I am trying to create a regex in C# to extract the artist, track number and song title from a filename named like: 01.artist - title.mp3
Right now I can't get the thing to work, and am having problems finding much relevant help online.
Here is what I have so far:
string fileRegex = "(?<trackNo>\\d{1,3})\\.(<artist>[a-z])\\s-\\s(<title>[a-z])\\.mp3";
Regex r = new Regex(fileRegex);
Match m = r.Match(song.Name); // song.Name is the filname
if (m.Success)
{
Console.WriteLine("Artist is {0}", m.Groups["artist"]);
}
else
{
Console.WriteLine("no match");
}
I'm not getting any matches at all, and all help is appreciated!
You might want to put ?'s before the <> tags in all your groupings, and put a + sign after your [a-z]'s, like so:
string fileRegex = "(?<trackNo>\\d{1,3})\\.(?<artist>[a-z]+)\\s-\\s(?<title>[a-z]+)\\.mp3";
Then it should work. The ?'s are required so that the contents of the angled brackets <> are interpreted as a grouping name, and the +'s are required to match 1 or more repetitions of the last element, which is any character between (and including) a-z here.
Your artist and title groups are matching exactly one character. Try:
"(?<trackNo>\\d{1,3})\\.(?<artist>[a-z]+\\s-\\s(?<title>[a-z]+)\\.mp3"
I really recommend http://www.ultrapico.com/Expresso.htm for building regular expressions. It's brilliant and free.
P.S. i like to type my regex string literals like so:
#"(?<trackNo>\d{1,3})\.(?<artist>[a-z]+\s-\s(?<title>[a-z]+)\.mp3"
Maybe try:
"(?<trackNo>\\d{1,3})\\.(<artist>[a-z]*)\\s-\\s(<title>[a-z]*)\\.mp3";
CODE
String fileName = #"01. Pink Floyd - Another Brick in the Wall.mp3";
String regex = #"^(?<TrackNumber>[0-9]{1,3})\. ?(?<Artist>(.(?!= - ))+) - (?<Title>.+)\.mp3$";
Match match = Regex.Match(fileName, regex);
if (match.Success)
{
Console.WriteLine(match.Groups["TrackNumber"]);
Console.WriteLine(match.Groups["Artist"]);
Console.WriteLine(match.Groups["Title"]);
}
OUTPUT
01
Pink Floyd
Another Brick in the Wall

Categories