0

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?

4
  • 3
    I think, better way would be using a regular expresison, and check if string matches it. Commented Jun 11, 2014 at 8:22
  • Hey, I am sorry for the late answer, yes I agree with you, using a regex would be better. Could you give an example? Commented Jun 13, 2014 at 10:51
  • As I understand, the would be real dates in places of 'date1' and 'date2', right? Commented Jun 13, 2014 at 11:37
  • Actually, they are just integers, it should be something like today's date - (10 + 5). Commented Jun 13, 2014 at 11:48

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.