What is the regular expression for "No quotes in a string"? - asp.net

I am trying to write a regular expression that doesn't allow single or double quotes in a string (could be single line or multiline string). Based on my last question, I wrote like this ^(?:(?!"|').)*$, but it is not working. Really appreciate if anybody could help me out here.

Just use a character class that excludes quotes:
^[^'"]*$
(Within the [] character class specifier, the ^ prefix inverts the specification, so [^'"] means any character that isn't a ' or ".)

Just use a regex that matches for quotes, and then negate the match result:
var regex = new Regex("\"|'");
bool noQuotes = !regex.IsMatch("My string without quotes");

Try this:
string myStr = "foo'baa";
bool HasQuotes = myStr.Contains("'") || myStr.Contains("\""); //faster solution , I think.
bool HasQuotes2 = Regex.IsMatch(myStr, "['\"]");
if (!HasQuotes)
{
//not has quotes..
}

This regular expression below, allows alphanumeric and all special characters except quotes(' and "")
#"^[a-zA-Z-0-9~+:;,/#&_#*%$!()\[\] ]*$"
You can use it like
[RegularExpression(#"^[a-zA-Z-0-9~+:;,/#&_#*%$!()**\[\]** ]*$", ErrorMessage = "Should not allow quotes")]
here use escape sequence() for []. Since its not showing in this post

Related

Use Replace function to remove "{ characters from string

I would like to remove "{ and replace it with {. The following is the line of code that I'm currently using.
var MyString = DataString.Replace(#""{", "");
The following is the error message I'm getting
Please advise
Thanks
You need to escape the quote that you want to replace using two quotes, so for your example:
var MyString = DataString.Replace(#"""{", "{");
Also see How to include quotes in a string for alternatives to use quotes in strings.
If you are expecting JSON data then what you really need is a JSON Parser for that. And if you just want to replace "{ to { then you simply need to escape and replace the string like below:
// Suppose the variable named str has a value of Hello"{ wrapped in double quotes
var strReplaced = str.Replace("\"{", "{");
Console.WriteLine($"strReplaced: {strReplaced}");
// This will result in strReplaced: Hello{

ASP.Net RegEx with ampersand and spaces

I am using the following regular expression to find words and phrases in a document. (Have to use regular expression and have to use \b.)
\b (zoo|a & b|dummy)\b
When I try to find matches in the following string
going to the zoo with a & b
a & b doesn't get matched. However, if I remove the leading and following space from the string and regex, making both a&b, it matches, but I do need to those spaces.
Use \s for spaces
string strRegex = #"\b\s(zoo|a\s&\sb|dummy)\b";
Regex myRegex = new Regex(strRegex, RegexOptions.None);
string strTargetString = #"going to the zoo with a & b";
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
Console.WriteLine(myMatch);
}

Find word (not containing substrings) in comma separated string

I'm using a linq query where i do something liike this:
viewModel.REGISTRATIONGRPS = (From a In db.TABLEA
Select New SubViewModel With {
.SOMEVALUE1 = a.SOMEVALUE1,
...
...
.SOMEVALUE2 = If(commaseparatedstring.Contains(a.SOMEVALUE1), True, False)
}).ToList()
Now my Problem is that this does'n search for words but for substrings so for example:
commaseparatedstring = "EWM,KI,KP"
SOMEVALUE1 = "EW"
It returns true because it's contained in EWM?
What i would need is to find words (not containing substrings) in the comma separated string!
Option 1: Regular Expressions
Regex.IsMatch(commaseparatedstring, #"\b" + Regex.Escape(a.SOMEVALUE1) + #"\b")
The \b parts are called "word boundaries" and tell the regex engine that you are looking for a "full word". The Regex.Escape(...) ensures that the regex engine will not try to interpret "special characters" in the text you are trying to match. For example, if you are trying to match "one+two", the Regex.Escape method will return "one\+two".
Also, be sure to include the System.Text.RegularExpressions at the top of your code file.
See Regex.IsMatch Method (String, String) on MSDN for more information.
Option 2: Split the String
You could also try splitting the string which would be a bit simpler, though probably less efficient.
commaseparatedstring.Split(new Char[] { ',' }).Contains( a.SOMEVALUE1 )
what about:
- separating the commaseparatedstring by comma
- calling equals() on each substring instead of contains() on whole thing?
.SOMEVALUE2 = If(commaseparatedstring.Split(',').Contains(a.SOMEVALUE1), True, False)

ASP.net validator regular expression and accented names / characters

I have a asp.net control that is using a regular expression to validate the users input for first name and last name. It works for up to 40 characters...and I think by the looks of the expression it also allows ' for names like O'Donald and maybe hypenated names too.
ValidationExpression="^[a-zA-Z''-'\s]{1,40}$"
My problem is with accented names/characters e.g. Spanish and French names that may contain for example ñ are not allowed. Does anyone know how to modify my expression to take this into account?
You want
\p{L}: any kind of letter from any language.
From regular-expressions.info
\p{L} or \pL is every character in the unicode table that has the property "letter". So it will match every letter from the unicode table.
You can use this within your character class like this
ValidationExpression="^[\p{L}''-'\s]{1,40}$"
Working C# test:
String[] words = { "O'Conner", "Smith", "Müller", "fooñ", "Fooobar12" };
foreach (String s in words) {
Match word = Regex.Match(s, #"
^ # Match the start of the string
[\p{L}''-'\s]{1,40}
$ # Match the end of the string
", RegexOptions.IgnorePatternWhitespace);
if (word.Success) {
Console.WriteLine(s + ": valid");
}
else {
Console.WriteLine(s + ": invalid");
}
}
Console.ReadLine();

Regular expression to convert substring to link

i need a Regular Expression to convert a a string to a link.i wrote something but it doesnt work in asp.net.i couldnt solve and i am new in Regular Expression.This function converts (bkz: string) to (bkz: show.aspx?td=string)
Dim pattern As String = "<bkz[a-z0-9$-$&-&.-.ö-öı-ış-şç-çğ-ğü-ü\s]+)>"
Dim regex As New Regex(pattern, RegexOptions.IgnoreCase)
str = regex.Replace(str, "<font color=""#CC0000"">$1</font>")
Generic remarks on your code: beside the lack of opening parentheses, you do redundant things: $-$ isn't incorrect but can be simplified into $ only. Same for accented chars.
Everybody will tell you that font tag is deprecated even in plain HTML: favor span with style attribute.
And from your question and the example in the reply, I think the expression could be something like:
\(bkz: ([a-z0-9$&.öışçğü\s]+)\)
the replace string would look like:
(bkz: <span style=""color: #C00"">$1</span>)
BUT the first $1 must be actually URL encoded.
Your regexp is in trouble because of a ')' without '('
Would:
<bkz:\s+((?:.(?!>))+?.)>
work better ?
The first group would capture what you are after.
Thanks Vonc,Now it doesnt raise error but also When i assign str to a Label.Text,i cant see the link too.Forexample after i bind str to my label,it should be viewed in view-source ;
<span id="Label1">(bkz: here)</span>
But now,it is in viewsource source;
<span id="Label1">(bkz: here)</span>

Resources