C# validate input syntax and replace values - c#

I am trying to make a function that validates an input string format and then replaces some values. The string should contain data in the following format:
string data = "'({today} - ({date1} + {date2}))', 'user', 'info'";
I want to make sure that the string is typed in the above format format(validate it), and if it is to replace the values of today, date1 and date2 with some values.
I am thinking of something like that, but I don't know if that is the best way:
if (data.Contains("{today}") && data.Contains("{date1}") && data.Contains("{date2}"))
{ }
Anybody can suggest something?

Here is what you asked, if I understood your comment correctly.
string data = "'({today} - ({date1} + {date2}))', 'user', 'info'"; // your string
string pattern = #"\{.*?\}"; // pattern that will match everything in format {anything}
Regex regEx = new Regex(pattern); //create regex using pattern
MatchCollection matches; // create collection of matches
matches = regEx.Matches(data); // get all matches from your string using regex
for (int i = 0; i < matches.Count; i++) // use this cycle to check if it s what you need
{
Console.WriteLine("{0}", matches[i].Value);
}

To validate your string, what you have suggested is fine. You could make it easier by checking for the negative:
if(!myString.Contains("{today}")
// handle error
if(!myString.Contains("{date1}")
// handle error
In order to replace the values, you can use String.Replace(...).
var myReplacedValue = myString.Replace("{today}", valueToRepalceWith);

Related

C# - Extract Date from String using StreamReader

How would I go about getting just the date from the following string?
"DateOfTest_01-30-2018-1_003"
This string is in position 8 in a CSV file, which I am looping through and parsing. What I have is:
while (!reader.EndOfStream) {
var splitLine = reader.ReadLine().SplitCommaSeparatedValues();
sample.RunDate = splitLine[8];
WriteLog("Run Date = " + sample.RunDate);}
So I need to extract characters from the string that fall between "_" and "-1" and convert the result to /mm/dd/yyyy format.
Thanks in advance for any assistance!
Better will be regular expression in this case: "(DateOfTest_)(\d{2}-\d{2}-\d{4})(-\d_\d{3})". Second group will be date. In c# you can use Regex.Match. MSDN
Use DateTime.ParseExact:
var culture = System.Globalization.CultureInfo.InvariantCulture;
var strToParse = splitLine[8].Substring(11, 10);
var date = DateTime.ParseExact(strToParse, "MM-dd-yyyy", culture);
var formattedStr = date.ToString("MM/dd/yyyy", culture);
You could use Regex matching to determine date string in the input.
var pattern = #"(?<=_)(.*?)(?=-1)";
var input = "DateOfTest_01-30-2018-1_003";
if (Regex.IsMatch(input, pattern))
{
var dateStr = Regex.Match(input, pattern);
var date = DateTime.ParseExact(dateStr.Value, "MM-dd-yyyy",null);
}
Unless you absolutely need the data at just that exact moment move your date parser outside of your reader.
After that, the answer really relies on whether or not the string in that field is always formatted the same way.
As others have pointed out, if the string is always of the same format you can substring the date out of the string. Then you can either do use one of the several built-in date format methods, or since it is formatted correctly, do a string.Replace("-", "//")
If the string format changes you'll need to try some regex to help you identify the substring to pull out.
My biggest point is that I think you should do this formatting of your field outside of your reader.
string TestString = "DateOfTest_01-30-2018-1_003";
Regex TestRegex = new Regex(#"(DateOfTest_)(\d{2}-\d{2}-20\d{2})(-\d_\d{3})");
string ExactDateFormat = "MM-dd-yyyy";
if (TestRegex.IsMatch(TestString))
{
Date = TestRegex.Match(TestString).Groups[2].ToString();
Date = DateTime.ParseExact(Date, ExactDateFormat, null).ToShortDateString();
}

How to remove DateTime substring from string

I have a bunch of strings, some of which have one of the following formats:
"TestA (3/12/10)"
"TestB (10/12/10)"
The DateTime portion of the strings will always be in mm/dd/yy format.
What I want to do is remove the whole DateTime part including the parenthesis. If it was always the same length I would just get the index of / and subtract that by the number of characters up to and including the (. But since the mm portion of the string could be one or two characters, I can't do that.
So is there a way to do a .Contains or something to see if the string contains the specified DateTime format?
You could use a Regular Expression to strip out the possible date portions if you can be sure they would consistently be in a certain format using the Regex.Replace() method :
var updatedDate = Regex.Replace(yourDate,#"\(\d{1,2}\/\d{1,2}\/\d{1,2}\)","");
You can see a working example of it here, which yields the following output :
TestA (3/12/10) > TestA
TestB (10/12/10) > TestB
TestD (4/5/15) > TestC
TestD (4/6/15) > TestD
You could always use a regular expression to replace the strings
Here is an example
var regEx = new Regex(#"\(\d{1,2}\/\d{1,2}\/\d{1,2}\)");
var text = regEx.Replace("TestA (3/12/10)", "");
Use a RegEx for this. I recommend:
\(\d{1,2}\/\d{1,2}\/\d{1,2}\)
See RegExr for it working.
Regex could be used for this, something such as:
string replace = "TestA (3/12/10) as well as TestB (10/12/10)";
string replaced = Regex.Replace(replace, "\\(\\d+/\\d+/\\d+\\)", "");
If I'm understanding this correctly you want to just acquire the test name of each string. Copy this code to a button click event.
string Old_Date = "Test SomeName(3/12/10)";
string No_Date = "";
int Date_Pos = 0;
Date_Pos = Old_Date.IndexOf("(");
No_Date = Old_Date.Remove(Date_Pos).Trim();
MessageBox.Show(No_Date, "Your Updated String", MessageBoxButton.OK);
To sum it up in one line of code
No_Date = Old_Date.Remove(Old_Date.IndexOf("(")).Trim();

Fixed string Regular Expression 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());

Replace part of a string with new value

I've got a scenario, wherein i need to replace the string literal with new text.
For example, if my string is "01HW128120", i will first check if the text contains "01HW" If yes, then replace that with the string "MachineID-".
So eventually i wanted "01HW128120" to be "MachineID-128120". Sometimes i do get the string as "1001HW128120" - In this case also i require to replace the "1001HW" with "MachineID-"
I tried the below code snippet, but this does not work to my expectation.
string sampleText = "01HW128120";
if(sampleText.Contains("01HW"))
sampleText = sampleText.Replace("01HW","MachineID-");
Any suggestion would be of great help to me.
Few Possible Search Values
If there are only a few possible combinations, you can simply do multiple tests:
string value = "01HW128120";
string replacement = "MachineID-";
if( value.Contains( "01HW" ) ) {
value = value.Replace( "01HW", replacement );
}
else if( value.Contains( "1001HW" ) ) {
value = value.Replace( "1001HW", replacement );
}
Assert.AreEqual( "MachineID-128120", value );
Many Possible Search Values
Of course, this approach quickly becomes unwieldy if you have a large quantity of possibilities. Another approach is to keep all of the search strings in a list.
string value = "01HW128120";
string replacement = "MachineID-";
var tokens = new List<string> {
"01HW",
"1001HW"
// n number of potential search strings here
};
foreach( string token in tokens ) {
if( value.Contains( token ) ) {
value = value.Replace( token, replacement );
break;
}
}
"Smarter" Matching
A regular expression is well-suited for string replacement if you have a manageable number of search strings but you perhaps need not-exact matches, case-insensitivity, lookaround, or capturing of values to insert into the replaced string.
An extremely simple regex which meets your stated requirements: 1001HW|01HW.
Demo: http://regexr.com?34djm
A slightly smarter regex: ^\d{2,4}HW
Assert position at start of string
Match 2-4 digits
Match the value "HW" literally
See also: Regex.Replace Method
If you just want to replace everything up to "01HW" with "MachineID-", you could use a generic regex:
sampleText = Regex.Replace(sampleText, "^.*01HW", "MachineID-");

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.

Categories