Declare constants that include special character - c#

I have a string that contains special character {,[,.. as follow:
"[{"name":"print","next":"null","proc":"printproc","func":"null"}]"
To assign the constant string to a variable, I have to do the following:
string s = "[{\"name\":\"print\",\"next\":\"null\",\"proc\":\"printproc\",\"func\":\"null\"}]";
or the compiler will throw out an error. Is there a less cumbersome way to declare the constant. I have tried to use # at the beginning of the string:
string s = #"[{"name":"print","next":"null","proc":"printproc","func":"null"}]";
But I got a compiler error as well. Saving the constant into a text file and load from it will work but it may be an overkill for me. Have anyone come across the same scenario in C# and have they come up with a work around?

Have you tried using single quotes to wrap the property names/values?
e.g. string s = #"[{'name':'print','next':'null','proc':'printproc','func':'null'}]"

you can put double qutes:
string s = #"[{""name"":""print""}]";
Or, put \
string s = "[{\"name\":\"print\"}]";
You can use this ' instead of "
Split your data with any way then use it

You could make a variable for each special character you want.
To show the concept, I tested this in a simple C# Console app.
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string quot = "\"";
string compound = "Now I can use " + quot + "quotation marks" + quot + " around a variable";
Console.WriteLine(compound);
}
}
}
The output is:
Now I can use "quotation marks" around a variable

Related

How to ignore case sensitive in this xpath c# selenium

I have a simple xpath:
driver.findelement(by.xpath("//li[contains(text(), 'chain')]").click()
This code is working but its not recognize chain in uppercase, how to ignore case sensitive in this xpath?
You can use the contains and translate functions together like this:
//li[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'chain')]
Use translate, but to make it shorter, you may translate only characters you are looking for
//li[contains(translate(text(), 'CHAIN', 'chain'), 'chain')]
If you are going to use this a lot, you may even write a method for that. I'll write in Java (sorry, not familiar with C#):
public static void main(String[] args) {
String l = "//li[" + containsTextIgnoringCase("StackOverflow") + "]";
System.out.println(l);
}
public static String containsTextIgnoringCase(String s) {
return String.format("contains(translate(text(), '%s', '%s'), '%s')", s.toUpperCase(), s.toLowerCase(), s);
}
output:
//li[contains(translate(text(), 'STACKOVERFLOW', 'stackoverflow'), 'stackoverflow')]
There's some space for optimization (not sure if it costs the effort, but still): translate only unique chars, and handle quotes, if passed in string
Use the value of chain in the way that assign it to a separate string variable and then apply .ToUpper() extension on it.
string strChain = "chain";
string getUpper = strChain.ToUpper();
It will give you cain in uppercase.
You can use it directly inside driver.findelement.

Pass old regular expression to new custom regular expression to exclude specific characters

I have a program with a lot of string constants being used to allow specific characters via regular expressions. I now have a list of characters I want to block everywhere, but I don't want to have to go back through all my old string constants and rewrite them. Instead, I want to create a list of restricted characters and edit that list in only one place (in case it changes in the future). I'll then run all the string constants through a custom regular expression.
I have the list of restricted characters defined in web.config like so:
<add key="RestrChar" value="\!#%<>|&;"/>
Calling a custom regular expression like this:
[RestrictCharRegExpress(ConstantStringName, ErrorMessage = CustomErrMsg)]
public string StringName
Class is defined as follows:
public class RestrictCharRegExpressAttribute : RegularExpressionAttribute
{
public RestrictCharRegExpressAttribute(string propRegex) : base(GetRegex(propRegex)){ }
private static string GetRegex(string propRegex)
{
string restrictedChars = ConfigurationManager.AppSettings.Get("RestrChar");
return Regex.Replace(propRegex, $"[{restrictedChars}]+", "");
}
}
Now this works when ConstantStringName specifically includes some of the characters I want to exclude like this:
public const string ConstantStringName = "^[-a-z A-Z.0-9/!&\"()]{1,40}$";
! and & are explicitly included so they will get replaced with nothing. But this won't work if the characters I'm trying to exclude aren't explicitly listed and are instead included via a list like this:
public const string ConstantStringName = "^[ -~\x0A\x0D]{1,40}$";
I've tried adding a negative lookahead like this:
return propRegex + "(?![" + restrictedChars + "])";
But that doesn't work in both cases. Also tried the negated set:
int i = propRegex.IndexOf(']');
if (i != -1)
{
propRegex = propRegex.Insert(i, "[^" + restrictedChars + "]");
return propRegex;
}
Still not working for both cases. Finally I tried character class subtraction:
int i = propRegex.IndexOf(']');
if (i != -1)
{
propRegex = propRegex.Insert(i, "-[" + restrictedChars + "]");
return propRegex;
}
And once again I achieved failure.
Does anyone have any other ideas how I can achieve my goal to exclude a set of characters no matter what set of regex rules are passed into my custom regular expression?
Actually figured out what I'm trying to do:
int indexPropRegex = propRegex.IndexOf('^');
string restrictedCharsAction = "(?!.*[" + restricedChars + "]);
propRegex = indexPropRegex == -1 ? propRegex.Insert(0, restrictedCharsAction) : propRegex.Insert(indexPropRegex +1, restrictedCharsAction);
return propRegex;

String concatenation using String interpolation

I've something like below.
var amount = "$1,000.99";
var formattedamount = string.Format("{0}{1}{0}", "\"", amount);
How can I achieve same using String interpolation?
I tried like below
var formattedamount1 = $"\"{amount}\"";
Is there any better way of doing this using string interpolation?
Update
Is there any better way of doing this using string interpolation
No, this is just string interpolation, you cant make the following any shorter and more readable really
var formattedamount1 = $"\"{amount}\"";
Original answer
$ - string interpolation (C# Reference)
To include a brace, "{" or "}", in the text produced by an
interpolated string, use two braces, "{{" or "}}". For more
information, see Escaping Braces.
Quotes are just escaped as normal
Example
string name = "Horace";
int age = 34;
Console.WriteLine($"He asked, \"Is your name {name}?\", but didn't wait for a reply :-{{");
Console.WriteLine($"{name} is {age} year{(age == 1 ? "" : "s")} old.");
Output
He asked, "Is your name Horace?", but didn't wait for a reply :-{
Horace is 34 years old.
Same thing you can achieve by doing:
var formattedamount1 = $"\"{amount}\"";
OR
var formattedamount1 = $#"""{amount}""";
It's basically allowing you to write string.Format(), but instead of using one string with "placeholders"({0}, {1}, .. {N}), you are directly writing/using your variable inside string.
Please read more about String Interpolation (DotNetPerls), $ - string interpolation to fully understand whats going on.
Just to give one more option, if you want to make sure you use the same quote at both the start and the end, you could use a separate variable for that:
string quote = "\"";
string amount = "$1,000.99";
string formattedAmount = $"{quote}{amount}{quote}";
I'm not sure I'd bother with that personally, but it's another option to consider.

Regex.Match doesnt work correctly

I have a string extension that was defined exactly like this:
public static string GetStringBetween(this string value, string start, string end)
{
start = Regex.Escape(start);
end = Regex.Escape(end);
GroupCollection matches = Regex.Match(value, start + #"([^)]*)" + end).Groups;
return matches[1].Value;
}
But when I call this:
string str = "The pre-inspection image A. Valderama (1).jpg of client Valderama is not...";
Console.WriteLine(str.GetStringBetween("pre-inspection image ", " of client"));
It doesn't write anything. But when the str value is like this:
string str = "The pre-inspection image A. Valderama.jpg of client Valderama is not...";
It works fine. Why was it like this?
My code is in C#, framework 4, build in VS2010 Pro.
Please help. Thanks in advance.
Because you specify to exclude the character ) in the capturing group of your regex: [^)] in #"([^)]*)"
And since ) appears in the first string: Valderama (1).jpg, it will not be able to match.
You probably want #"(.*)" instead.

Changing an "." to an "_" in a C# string

I'm developing a piece of software in C# and the end result is an Excel spreadsheet. The title of the spreadsheet is created using several variables to explain exactly what the spreadsheet is. One of the variables is a string which contains data like this:
'1.1.1'
I need to convert it at the point of creating the spreadsheet to be:
'1_1_1'
I have tried using the String.Replace method but it just seems to ignore it. Any ideas?
Best Regards
I bet you doing this:
myString.Replace(".","_");
When you should be doing this:
myString = myString.Replace(".","_");
Remember, in .Net strings are immutable, so any changes result in a new string.
Chances are you're ignoring the result of string.Replace. You need:
text = text.Replace('.', '_');
Just calling Replace doesn't change the existing string - it creates a new string and returns it. Strings are immutable in .NET - they never change after creation.
When you use string.Replace are you remembering that you have to assign it?
yourString.Replace(".", "_");
Will do nothing.
string newString = yourString.Replace(".", "_");
will return the string with the dots replaced with underscores.
If I had to guess, you're not capturing the value returned by String.Replace. Strings are immutable, so String.Replace returns a new string, which you need to store a reference to.
string foo = "1.1.1";
foo = foo.Replace('.', '_');
String input = "1.1.1";
input = input.Replace(".", "_");
strings are immutable, so make sure you're using it like this:
string myString = "1.1.1";
myString = myString.Replace('.', '_');
String.Replace is the right way to do this:
private void button1_Click(object sender, RoutedEventArgs e) {
String myNumbers = "1.1.1";
Console.WriteLine("after replace: " + myNumbers);
myNumbers = myNumbers.Replace(".", "_");
Console.WriteLine("after replace: " + myNumbers);
}
will produce:
after replace: 1.1.1
after replace: 1_1_1

Categories

Resources