Fixed string Regular Expression C# - c#

Hi all I want to know something regarding to fixed-string in regular expression.
How to represent a fixed-string, regardless of special characters or alphanumeric in C#?
For eg; have a look at the following string:
infinity.world.uk/Members/namelist.aspx?ID=-1&fid=X
The entire string before X will be fixed-string (ie; the whole sentence will appear the same) BUT only X will be the decimal variable.
What I want is that I want to append decimal number X to the fixed string. How to express that in terms of C# regular expression.
Appreciate your help

string fulltext = "inifinity.world.uk/Members/namelist.aspx?ID=-1&fid=" + 10;

if you need to modify existing url, dont use regex, string.Format or string.Replace you get problem with encoding of arguments
Use Uri and HttpUtility instead:
var url = new Uri("http://infinity.world.uk/Members/namelist.aspx?ID=-1&fid=X");
var query = HttpUtility.ParseQueryString(url.Query);
query["fid"] = 10.ToString();
var newUrl = url.GetLeftPart(UriPartial.Path) + "?" + query;
result: http://infinity.world.uk/Members/namelist.aspx?ID=-1&fid=10
for example, using query["fid"] = "%".ToString(); you correctly generate http://infinity.world.uk/Members/namelist.aspx?ID=-1&fid=%25
demo: https://dotnetfiddle.net/zZ9Y1h

String.Format is one way of replacing token values in a string, if that's what you want. In the example below, the {0} is a token, and String.Format takes the fixedString and replaces the token with the value of myDecimal.
string fixedString = "infinity.world.uk/Members/namelist.aspx?ID=-1&fid={0}";
decimal myDecimal = 1.5d;
string myResultString = string.Format(fixedString, myDecimal.ToString());

Related

How can i create a dynamic string format in C#

I have as input the string format CST-000000 and an integer with value 1
Upon using
string result = string.Format("CST-000000", 1);
the expected result should be CST-000001 instead of CST-000000
How could i create this string format dynamically?
For example
- CST-000 should produce CST-001
- HELLO000 should produce HELLO001
- CUSTOMER0000 should produce CUSTOMER0001
Assuming that:
You receive your format string from somewhere and you can't control what it looks like
Your format string ends with 1 or more zeros
If the format string is e.g. CST-00000 and your value is 123, you want the result to be CST-00123
You can do something like this:
Inspect your format string, and separate out the stuff at the beginning from the zeros at the end. It's easy to do this with Regex, e.g.:
string format = "CST-000000";
// "Zero or more of anything, followed by one or more zeros at the end of the string"
var match = Regex.Match(format, "(.*?)(0+)$");
if (!match.Success)
{
throw new ArgumentException("Format must end with one or more zeros");
}
string prefix = match.Groups[1].Value; // E.g. CST-
string zeros = match.Groups[2].Value; // E.g. 000000
Once you have these, note the "Zero placeholder" in this list of custom numeric format strings -- you can write e.g. 123.ToString("0000") and the output will be 0123. This lets you finish off with:
int value = 123;
string result = prefix + value.ToString(zeros);
See it on dotnetfiddle
String.Format requires a placeholder {n} with a zero-based argument number. You can also add it a format {n:format}.
string result = String.Format("CST-{0:000000}", 1);
You can also use String interpolation
string result = $"CST-{1:000000}"
The difference is that instead of a placeholder you specify the value directly (or as an expression). Instead of the Custom numeric format string, you can also use the Standard numeric format string d6: $"CST-{1:d6}"
If you want to change the format template dynamically, String.Format will work better, as you can specify the format and the value as separate arguments.
(Example assumes an enum FormatKind and C# >= 8.0)
int value = 1;
string format = formatKind switch {
FormatKind.CstSmall => "CST-{0:d3}",
FormatKind.CstLarge => "CST-{0:d6}",
FormatKind.Hello => "HELLO{0:d3}",
FormatEnum.Customer => "CUSTOMER{0:d4}"
};
string result = String.Format(format, value);
Also note that the value to be formatted must be of a numeric type. Strings cannot be formatted.
See also: Composite formatting
It seems .toString("CST-000"), .toString("HELLO000") and so on, does the trick.
ToString and String.Format can do much more than use predefined formats.
For example :
string result = string.Format("CST-{0:000000}", 1);
string result = 1.ToString("CST-000000");
Should both do what you want.
(Of course you could replace "1" by any variable, even a decimal one).

Interpolation in the middle of a string

I want to interpolation in the middle of a string, but I cannot use String.Format, because the string contains {} curly brackets.
This is what I have tried so far:
string code = "(function(){var myvariable = $"{variableToBeInterpolated}"});"
Returns: ) expected ; expected
Edit: I tried the following snippet, the interpolation is now working, but the code is not executed in the browser.
"(function(){var myvariable=" + $"{myvariable c#}" + ")});"
General Information
With C# version 6, extensive string interpolation capabilities have been added to the language.
String interpolation provides a more readable and convenient syntax to
create formatted strings than a string composite formatting feature.
To solve your problem, please have a look at the special characters section of the documentation, which reads the following:
To include a brace, "{" or "}", in the text produced by an
interpolated string, use two braces, "{{" or "}}".
Example
var variable = 10;
var code = $"(function() {{ var myVariable = {variable} }});";
Console.WriteLine(code);
Output: (function() { var myVariable = 10 });
Have you tried:
string someVariable = "test";
string code = $"(function()'{{var myvariable = ({someVariable} in c#)}});"
Using $ in C# is string interpolation. Added in C# 6
learn.microsoft.com
Why do you want to interpolate in the middle, rather put $ in front. And for { you need to use {{. (the same applies for })
string code = $"(function(){{ var myvariable = {myvariable} }});";

How to get the string data which is outside of parenthesis in C#

I need to get the data which is outside of parenthesis
string data = "English(Language)";
string result= "English";
The result should display the text "English".
I tried with Regex but not able to get the desired result.
Easiest solution that I can think of:
string data = "English(Language)";
string result = data.Substring(0, data.IndexOf('('));
That is of course, if you never need the data within the parenthesis.
Another way to do it is by using String.Split:
string data = "English(Language)";
string result = data.Split('(')[0];
This is marginally slower than the first example since it needs to allocate memory for an array.
The third way to do it is via regular-expressions:
string data = "English(Language)";
var pattern = new Regex("(\\w+\\s?)\\((\\w+)\\)", RegexOptions.Compiled);
string result = pattern.Match(data).Groups[1].Value;
This is the slowest of all the examples, but captures both "English" and "Language". It also allows for whitespace \s? between English and (Language).
A great tool for testing regular expressions is RegexPal, just remember to escape everything when you move it over to C#.
Here is a fiddle, testing the performance of all options.
Try:
string input = "English(Language)";
string regex = "(\\(.*\\))";
string output = Regex.Replace(input, regex, "");
You will need that:
using System.Text.RegularExpressions;
If you dont bother to use Regex, the below solution works fine.
string data = "English(Language)";
string result = Regex.Match(data, #"(.*)\(.*\)").Groups[1].Value;
Console.WriteLine(result); // English
Hi take a look at the Split methods:
string data = "English(Language)";
string result= "English";
var value = data.Split('(').First();
Console.WriteLine (value);
Result :
English
xd or just:
string data = "English(Language)";
string result = data.Replace("(Language)", "");

Regular expression for parsing CSV

I'm trying to parse a CSV file in C#. Split on commas (,). I got it to work with this:
[\t,](?=(?:[^\"]|\"[^\"]*\")*$)
Splitting this string:
2012-01-06,"Some text with, comma",,"300,00","143,52"
Gives me:
2012-01-06
"Some text with, comma"
"300,00"
"143,52"
But I can't figure out how to lose the "" from the output so I get this instead:
2012-01-06
Some text with, comma
300,00
143,52
Any suggestions?
If you are trying to parse a CSV and using .NET, don't use regular expressions. Use a component that was created for this purpose. See the question CSV File Imports in .Net.
I know the CSV specification looks simple enough, but trust me, you are in for heartache and destruction if you continue down this path.
Why are you using regular expressions for this? Ensuring the file is well-formed?
You can use String.Replace()
String s = "Some text with, comma";
s = s.Replace("\"", "");
// After matched
String line = 2012-01-06,"Some text with, comma",,"300,00","143,52";
String []fields = line.Split(',');
for (int i = 0; i < fields.Length; i++)
{
// Call a function to remove quotes
fields[i] = removeQuotes(fields[i]);
}
String removeQuotes(String s)
{
return s.Replace("\"", "");
}
So, something like this. Again, I wouldn't use RegEx for this purpose, but YMMV.
var sp = Regex.Split(a, "[\t,](?=(?:[^\"]|\"[^\"]*\")*$)")
.Select(s => Regex.Replace(s.Replace("\"\"","\""),"^\"|\"$","")).ToArray();
So, the idea here is that first of all, you want to replace double double quotes with a single double quote. And then that string is fed to the second regex which simply removes double quotes at the beginning and end of the string.
The reason for the first replace is because of strings like this:
var a = "1999,Chevy,\"Venture \"\"Extended Edition, Very Large\"\" Dude\",\"\",\"5000.00\"";
So, this would give you a string like this: ""Extended Edition"", and the double quotes need to be changed to single quotes.

How to get id from String with using Regex

I want to get only number id from string. result : 123456
var text = "http://test/test.aspx?id=123456dfblablalab";
EDIT:
Sorry, Another number can be in the text. I want to get first number after id.
var text = "http://test/test.aspx?id=123456dfbl4564dsf";
Use:
Regex.Match(text, #"id=(\d+)").Groups[1].Value;
It depends on the context - in this case it looks like you are parsing a Uri and a query string:
var text = "http://test/test.aspx?id=123456dfblablalab";
Uri tempUri = new Uri(text);
NameValueCollection query = HttpUtility.ParseQueryString(tempUri.Query);
int number = int.Parse(new string(query["id"].TakeWhile(char.IsNumber).ToArray()));
Someone will give you a C# implementation, but it's along the lines of
/[\?\&]id\=([0-9]+)/
Which will match either &id=123456fkhkghkf or ?id=123456fjgjdfgj (so it'll get the value wherever it is in the URL) and capture the number as a match.

Categories