Quick Help With Regex C# - c#

How can I match on the following string: A constant string name, followed by a period, followed by any positive integer, followed by another dot.
For example I want to find anything like this:
SomeText.1.
SomeText.99.
SomeText.100.
SomeText.1002.

Regex.Match(input, #"SomeText\.\d+\.");

Try something like this:
^SomeText\.\d+\.$
To explain:
The ^ means the beginning of the line, as $ means the end of the line. This ensure that the entire string matches the expression, not that something in it happens to match the pattern.
The SomeText part is self explanatory.
The \. means "match a single .". The \ is required to escape the meaning of the period, which by itself would mean "Any single character"
The \d+ means "One or more digits".
Then the \. again, and finally $ to signify that's where we expect the string to end.

If you want to be able to retrieve the number, try:
var exp = new Regex(#"SomeText\.(?<number>\d+)\.",RegexOptions.Compiled);
foreach(string s in allStrings)
{
var collection = exp.Match(s);
if (collection.Success)
{
int myNumber = int.parse(collection.Groups["number"].Value);
// ...
}
}

Your regex would look like SomeText\.\d+\.
Which, in c# code would be
var result = Regex.Match(stringToMatch, #"SomeText\.\d+\.");

Related

C# Capturing the first match with regex

I've got an input string that looks like this:
url=https%3A%2F%2Fdomain.com%2Fsale-deal%3Futm_source%3Dinsider-primary-action%3Dinsider-primary-action&utm_source=FB
or
url=https%3A%2F%2Fdomain.com%2Fsale&utm_source=FB&sub_id1=M12
the string sometimes has or non %3Futm_source
how to get link between url= and %3Futm_source% or &utm_source
Regex reg = new Regex(#"url=(https%3A%2F%2Fdomain.com[a-zA-Z0-9-_/%\.]+)%3Futm_source|&utm_source");
Match result = reg.Match(inPut);
Console.WriteLine(result.Groups[1].Value));
it always get from url= to &utm_source
You can use this
(?<=url=).*?(?=%3Futm_source|&utm_source)
(?<=url=) Positive look behind. matches url=.
.* - Matches anything except new line.
(?=%3Futm_source|&utm_source) - Positive look ahead. Matches %3Futm_source or &utm_source
Demo

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

Check if an expression is a match with regex

In C# I have two strings: [I/text] and [S/100x20].
So, the first one is [I/ followed by text and ending in ].
And the second is [S/ followed by an integer, then x, then another integer, and ending in ].
I need to check if a given string is a match of one of this formats. I tried the following:
(?<word>.*?) and (?<word>[0-9]x[0-9])
But this does not seem to work and I am missing the [I/...] and [S/...] parts.
How can I do this?
This should do nicely:
Regex rex = new Regex(#"\[I/[^\]]+\]|\[S/\d+x\d+\]");
If the text in [I/text] is supposed to include only alphanumeric characters then #Oleg's use of the \w instead of [^\]] would be better. Also using + means there needs to be at least one of the preceding character class, and the * allows class to be optional. Adjust as needed..
And use:
string testString1 = "[I/text]";
if(rex.IsMatch(testString1))
{
// should match..
}
string testString2 = "[S/100x20]";
if(rex.IsMatch(testString2))
{
// should match..
}
Following regex does it. Matches the whole string
"(\[I/\w+\])|(\[S/\d+x\d+\])"
([I/\w+])
(S/\d+x\d+])
the above works.
use http://regexr.com?34543 to play with your expressions

Trouble creating a Regex expression

I'm trying to create a regex expression what will accept a certain format of command. The pattern is as follows:
Can start with a $ and have two following value 0-9,A-F,a-f (ie: $00 - $FF)
or
Can be any value except for "&<>'/"
*if the value start with $ the next two values after need to be a valid hex value from 00-ff
So far I have this
Regex correctValue = new Regex("($[0-9a-fA-F][0-9a-fA-F])");
Any help will be greatly appreciated!
You just need to add "\" symbol before your "$" and it works:
string input = "$00";
Match m = Regex.Match(input, #"^\$[0-9a-fA-F][0-9a-fA-F]$");
if (m.Success)
{
foreach (Group g in m.Groups)
Console.WriteLine(g.Value);
}
else
Console.WriteLine("Didn't match");
If I'm following you correctly, the net result you're looking for is any value that is not in the list "&<>'/", since any combination of $ and two alphanumeric characters would also not be in that list. Thus you could make your expression:
Regex correctValue = new Regex("[^&<>'/]");
Update: But just in case you do need to know how to properly match the $00 - $FF, this would do the trick:
Regex correctValue = new Regex("\$[0-9A-Fa-f]{2}");
In Regular Expression $ use for Anchor assertion, and means:
The match must occur at the end of the string or before \n at the end of the line or string.
try using [$] (Character Class for single character) or \$ (Character Escape) instead.

Simple regex question C#

I need to match the string that is shown in the window displayed below :
8% of setup_av_free.exe from software-files-l.cnet.com Completed
98% of test.zip from 65.55.72.119 Completed
[numeric]%of[filename]from[hostname | IP address]Completed
I have written the regex pattern halfway
if (Regex.IsMatch(text, #"[\d]+%[\s]of[\s](.+?)(\.[^.]*)[\s]from[\s]"))
MessageBox.Show(text);
and I now need to integrate the following regex into my code above
ValidIpAddressRegex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$";
ValidHostnameRegex = "^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$";
The 2 regex were taken from this link. These 2 regex works well when i use the Regex.ismatch to match "123.123.123.123" and "software-files-l.cnet.com" . However i cannot get it to work when i intergrate both of them to my existin regex code. I tried several variant but not able to get it to work. Can someone guide me to integrate the 2 regex to my existing code. Thanks in advance.
You can certainly combine all these regular expressions into one, but I'd recommend against it. Consider this method, first it checks wether your input text has the correct form overall, then it checks if the "from" part is an IP address or a hostname.
bool CheckString(string text) {
const string ValidIpAddressRegex = #"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$";
const string ValidHostnameRegex = #"^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$";
var match = Regex.Match(text, #"[\d]+%[\s]of[\s](.+?)(\.[^.]*)[\s]from[\s](\S+)");
if(!match.Success)
return false;
string address = match.Groups[3].Value;
return Regex.IsMatch(address, ValidIpAddressRegex) ||
Regex.IsMatch(address, ValidHostnameRegex);
}
It does what you want and is much more readable and than single monster-sized regular expression. If you aren't going to call this method millions of time in a loop there is no reason to be concerned about it being less performant that single regex.
Also, in case you aren't aware of that the brackets around \d or \s aren't necessary.
The "Problem" that those two regexes do not match your string is that they start with ^ and end with $
^ means match the start of the string (or row if the m modifier is activated)
$ means match the end of the string (or row if the m modifier is activated)
When you try it this is true but in your real text they are in the middle of the string, so it is not matched.
Try just remove the ^ at the very beginning and the $ at the very end.
Here you go.
^[\d]+%[\s+]of[\s+](.+?)(\.[^.]*)[\s+]from[\s+]((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])|((([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])))[\s+]Completed
Remove the ^ and $ characters from the ValidIpAddressRegex and ValidHostnameRegex samples above, and add them separated by the or character (|) enclosed by parentheses.
You could use this, its should work for all cases. I mightve accidentally deleted a character while formatting so let me know if it doesnt work.
string captureString = "8% of setup_av_free.exe from software-files-l.cnet.com Completed";
Regex reg = new Regex(#"(?<perc>\d+)% of (?<file>\w+\.\w+) from (?<host>" +
#"(\d+\.\d+.\d+.\d+)|(((https?|ftp|gopher|telnet|file|notes|ms-help):" +
#"((//)|(\\\\))+)?[\w\d:##%/;$()~_?\+-=\\\.&]*)) Completed");
Match m = reg.Match(captureString);
string perc = m.Groups["perc"].Value;
string file = m.Groups["file"].Value;
string host = m.Groups["host"].Value;

Categories