Check Format of a string - c#

What is the smallest amount of C# possible to Check that a String fits this format #-##### (1 number, a dash then 5 more numbers).
It seems to me that a regular expression could do this quick (again, I wish I knew regular expressions).
So, here is an example:
public bool VerifyBoxNumber (string boxNumber)
{
// psudo code
if (boxNumber.FormatMatch("#-#####")
return true;
return false;
}
If you know real code that will make the above comparison work, please add an answer.

private static readonly Regex boxNumberRegex = new Regex(#"^\d-\d{5}$");
public static bool VerifyBoxNumber (string boxNumber)
{
return boxNumberRegex.IsMatch(boxNumber);
}

return Regex.IsMatch(boxNumber, #"^\d-\d{5}$");

^\d-\d{5}$ would be a regexp that matches only this pattern.

Related

Regex for string without spacial characters or spaces [duplicate]

How do I check a string to make sure it contains numbers, letters, or space only?
In C# this is simple:
private bool HasSpecialChars(string yourString)
{
return yourString.Any(ch => ! char.IsLetterOrDigit(ch));
}
The easiest way it to use a regular expression:
Regular Expression for alphanumeric and underscores
Using regular expressions in .net:
http://www.regular-expressions.info/dotnet.html
MSDN Regular Expression
Regex.IsMatch
var regexItem = new Regex("^[a-zA-Z0-9 ]*$");
if(regexItem.IsMatch(YOUR_STRING)){..}
string s = #"$KUH% I*$)OFNlkfn$";
var withoutSpecial = new string(s.Where(c => Char.IsLetterOrDigit(c)
|| Char.IsWhiteSpace(c)).ToArray());
if (s != withoutSpecial)
{
Console.WriteLine("String contains special chars");
}
Try this way.
public static bool hasSpecialChar(string input)
{
string specialChar = #"\|!#$%&/()=?»«#£§€{}.-;'<>_,";
foreach (var item in specialChar)
{
if (input.Contains(item)) return true;
}
return false;
}
String test_string = "tesintg#$234524##";
if (System.Text.RegularExpressions.Regex.IsMatch(test_string, "^[a-zA-Z0-9\x20]+$"))
{
// Good-to-go
}
An example can be found here: http://ideone.com/B1HxA
If the list of acceptable characters is pretty small, you can use a regular expression like this:
Regex.IsMatch(items, "[a-z0-9 ]+", RegexOptions.IgnoreCase);
The regular expression used here looks for any character from a-z and 0-9 including a space (what's inside the square brackets []), that there is one or more of these characters (the + sign--you can use a * for 0 or more). The final option tells the regex parser to ignore case.
This will fail on anything that is not a letter, number, or space. To add more characters to the blessed list, add it inside the square brackets.
Use the regular Expression below in to validate a string to make sure it contains numbers, letters, or space only:
[a-zA-Z0-9 ]
You could do it with a bool. I've been learning recently and found I could do it this way. In this example, I'm checking a user's input to the console:
using System;
using System.Linq;
namespace CheckStringContent
{
class Program
{
static void Main(string[] args)
{
//Get a password to check
Console.WriteLine("Please input a Password: ");
string userPassword = Console.ReadLine();
//Check the string
bool symbolCheck = userPassword.Any(p => !char.IsLetterOrDigit(p));
//Write results to console
Console.WriteLine($"Symbols are present: {symbolCheck}");
}
}
}
This returns 'True' if special chars (symbolCheck) are present in the string, and 'False' if not present.
A great way using C# and Linq here:
public static bool HasSpecialCharacter(this string s)
{
foreach (var c in s)
{
if(!char.IsLetterOrDigit(c))
{
return true;
}
}
return false;
}
And access it like this:
myString.HasSpecialCharacter();
private bool isMatch(string strValue,string specialChars)
{
return specialChars.Where(x => strValue.Contains(x)).Any();
}
Create a method and call it hasSpecialChar with one parameter
and use foreach to check every single character in the textbox, add as many characters as you want in the array, in my case i just used ) and ( to prevent sql injection .
public void hasSpecialChar(string input)
{
char[] specialChar = {'(',')'};
foreach (char item in specialChar)
{
if (input.Contains(item)) MessageBox.Show("it contains");
}
}
in your button click evenement or you click btn double time like that :
private void button1_Click(object sender, EventArgs e)
{
hasSpecialChar(textbox1.Text);
}
While there are many ways to skin this cat, I prefer to wrap such code into reusable extension methods that make it trivial to do going forward. When using extension methods, you can also avoid RegEx as it is slower than a direct character check. I like using the extensions in the Extensions.cs NuGet package. It makes this check as simple as:
Add the [https://www.nuget.org/packages/Extensions.cs][1] package to your project.
Add "using Extensions;" to the top of your code.
"smith23#".IsAlphaNumeric() will return False whereas "smith23".IsAlphaNumeric() will return True. By default the .IsAlphaNumeric() method ignores spaces, but it can also be overridden such that "smith 23".IsAlphaNumeric(false) will return False since the space is not considered part of the alphabet.
Every other check in the rest of the code is simply MyString.IsAlphaNumeric().
Based on #prmph's answer, it can be even more simplified (omitting the variable, using overload resolution):
yourString.Any(char.IsLetterOrDigit);
No special characters or empty string except hyphen
^[a-zA-Z0-9-]+$

c# if contains AND/OR

Is there a variant of this?
if (blabla.Contains("I'm a noob") | blabla.Contains("sry") | blabla.Contains("I'm a noob "+"sry"))
{
//stuff
}
like:
if (blabla.Contains("I'm a noob) and/or ("sry")
{
//stuff
}
Help is appreciated!
You can't collapse it quite as far as you asked, but you can do:
if (blabla.Contains("I'm a noob") || blabla.Contains("sry"))
{
//stuff
}
The "and" case is handled here because a string with both would actually pass both of the statements in the "Or".
As far as I'm aware, there are no built-in methods to do this. But with a little LINQ and extension methods, you can create your own methods that will check to see if a string contains any or all tokens:
public static class ExtensionMethods{
public static bool ContainsAny(this string s, params string[] tokens){
return tokens.Any(t => s.Contains(t));
}
public static bool ContainsAll(this string s, params string[] tokens){
return tokens.All(t => s.Contains(t));
}
}
You could use it like this (remember, params arrays take a variable number of parameters, so you're not limited to just two like in my example):
var str = "this is a string";
Console.WriteLine(str.ContainsAny("this", "fake"));
Console.WriteLine(str.ContainsAny("doesn't", "exist"));
Console.WriteLine(str.ContainsAll("this", "is"));
Console.WriteLine(str.ContainsAll("this", "fake"));
Output:
True
False
True
False
Edit:
For the record, LINQ is not necessary. You could just as easily write them this way:
public static class ExtensionMethods{
public static bool ContainsAny(this string s, params string[] tokens){
foreach(string token in tokens)
if(s.Contains(token)) return true;
return false;
}
public static bool ContainsAll(this string s, params string[] tokens){
foreach(string token in tokens)
if(!s.Contains(token)) return false;
return true;
}
}
var arr = new[]{"I'm a noob" ,"sry", "I'm a noob +sry"};
if(arr.Any(x => blabla.Contains(x)))
{
}
You can use a regex:
Regex r = new Regex("I'm a noob|sry|I'm a noob sry");
if(r.IsMatch(blabla)) {
//TODO: do something
}
Regular expressions have other advanced features like: a* matches with the empty string, a, aa, aaa,...
The funny part is that if you "compile" the regex (for instance using new Regex("I'm a noob|sry|I'm a noob sry",RegexOptions.Compiled), C# will turn it automatically into the fastest solution mechanism possible. For instance if blabla is a 100k chars string, you will only run once over the entire string. And for instance redundant parts like I'm a noob sry will be omitted automatically.

Case Insensitive comparison in C# [duplicate]

This question already has answers here:
Case insensitive 'Contains(string)'
(29 answers)
Closed 9 years ago.
I am comparing two strings using following code
string1.Contains(string2)
but i am not getting results for case insensitive search. Moreover I cant use String.Compare coz i dont want to match the whole name as the name is very big.
My need is to have case insensitive search and the search text can be of any length which the String1 contains.
Eg Term************** is the name.
I enter "erm" in textbox den i get the result. but when i enter "term" i dont get any result.
Can anyone help me :)
Try this:
string.Equals("this will return true", "ThIs WiLL ReTurN TRue", StringComparison.CurrentCultureIgnoreCase)
Or, for contains:
if (string1.IndexOf(string2, StringComparison.CurrentCultureIgnoreCase) >= 0)
I prefer an extension method like this.
public static class StringExtensions
{
public static bool Contains(this string source, string value, StringComparison compareMode)
{
if (string.IsNullOrEmpty(source))
return false;
return source.IndexOf(value, compareMode) >= 0;
}
}
Notice that in this way you could avoid the costly transformation in upper or lower case.
You could call the extension using this syntax
bool result = "This is a try".Contains("TRY", StringComparison.InvariantCultureIgnoreCase);
Console.WriteLine(result);
Please note: the above extension (as true for every extension method) should be defined inside a non-nested, non-generic static class See MSDN Ref
Convert both strings to a same case, either upper or lower.
string1.ToUpper().Contains(string2.ToUpper());
Why not this:
if (string1.IndexOf(string2, StringComparison.OrdinalIgnoreCase) >= 0)
{
}
string1.ToUpperInvariant().Contains(string2.ToUpperInvariant());
You can either convert both strings to uppercase, or use regular expressions:
using System.Text.RegularExpressions;
class Program {
static void Main(string[] args) {
string string1 = "TermSomething";
string string2 = "term";
bool test1 = string1.ToUpperInvariant().Contains(string2.ToUpperInvariant());
bool test2 = Regex.IsMatch(string1, Regex.Escape(string2), RegexOptions.IgnoreCase);
}
}
Note that if you use regular expressions you should escape the search string, so that special regex characters are interpreted literally.
Regex.IsMatch(string1,string2,RegexOptions.IgnoreCase);
This returns boolean value.....

Is there a way to evaluate more than one string inside of a string.contains() method?

if (description.ToUpper().Contains("BOUGHT") || description.ToUpper().Contains("PURCHASE"))
The code above is what I have and I wondered if I had a longer list of strings for the same condition, how I would do it without making the code too long. Maybe a lambda expression?
No, there is no built in function. But it's not hard to write it yourself:
string[] needles = new string[]{"BOUGHT", "PURCHASE"};
string haystack = description.ToUpperInvariant();
bool found = needles.Any(needle=> haystack.Contains(needle));
I only convert hackstack to upper once to improve performance.
Alternatively you could use IndexOf(needle, StringComparison.OrdinalIgnoreCase)>=0:
string[] needles = new string[]{"BOUGHT", "PURCHASE"};
string haystack = description;
bool found = needles.Any(needle=> haystack.IndexOf(needle, StringComparison.OrdinalIgnoreCase)>=0);
You should not use ToUpper() here, since that uses the current culture. Using the current culture can lead to unexpected problems on some computers, for example i does not uppercase to I when using the Turkish culture.
There might still some subtle problems remaining where ToUpperInvariant() on both sides and a case insensitive comparison might return different results, but that's only relevant if you have unusual characters in both your haystack and needles.
You can rework the code to something like this:
var words = new[] { "BOUGHT", "PURCHASE" };
var desc = description.ToUpper();
if(words.Any(w => description.Contains(w)) {
// something matched
}
if (someCollectionOfStrings.Any(string => originalString.Contains(string))
{
//stuff
}
Use a regular expression:
if (Regex.IsMatch(description, "purchase|bought", RegexOptions.IgnoreCase)) {
// ...
}
Regex.IsMatch(input, string.Join("|", strings));
You might have to escape the strings if they contain Regex control characters.
public static bool ContainsOneOfManyIgnoreCase(this string str, params string [] items)
{
return items.Any(x => str.IndexOf(x, StringComparison.CurrentCultureIgnoreCase) != -1);
}

string manipulation check and replace with fastest method

I have some strings like below:
string num1 = "D123_1";
string num2 = "D123_2";
string num3 = "D456_11";
string num4 = "D456_22";
string num5 = "D_123_D";
string num5 = "_D_123";
I want to make a function that will do the following actions:
1- Checks if given string DOES HAVE an Underscore in it, and this underscore should be after some Numbers and Follow with some numbers: in this case 'num5' and 'num6' are invalid!
2- Replace the numbers after the last underscore with any desired string, for example I want 'num1 = "D123_1"' to be changed into 'D123_2'
So far I came with this idea but it is not working :( First I dont know how to check for criteria 1 and second the replace statement is not working:
private string CheckAndReplace(string given, string toAdd)
{
var changedString = given.Split('_');
return changedString[changedString.Length - 1] + toAdd;
}
Any help and tips will be appriciated
What you are looking for is a regular expression. This is (mostly) from the top of my head. But it should easily point you in the right direction. The regular expression works fine.
public static Regex regex = new Regex("(?<character>[a-zA-Z]+)(?<major>\\d+)_(?<minor>\\d+)",RegexOptions.CultureInvariant | RegexOptions.Compiled);
Match m = regex.Match(InputText);
if (m.Succes)
{
var newValue = String.Format("{0}{1}_{2}"m.Groups["character"].Value, m.Groups["major"].Value, m.Groups["minor"].Value);
}
In your code you split the String into an array of strings and then access the wrong index of the array, so it isn't doing what you want.
Try working with a substring instead. Find the index of the last '_' and then get the substring:
private string CheckAndReplace(string given, string toAdd) {
int index = given.LastIndexOf('_')+1;
return given.Substring(0,index) + toAdd;
}
But before that check the validity of the string (see other answers). This code fragment will break when there's no '_' in the string.
You could use a regular expression (this is not a complete implementation, only a hint):
private string CheckAndReplace(string given, string toAdd)
{
Regex regex = new Regex("([A-Z]*[0-9]+_)[0-9]+");
if (regex.IsMatch(given))
{
return string.Concat(regex.Match(given).Groups[1].Value, toAdd);
}
else
{
... do something else
}
}
Use a good regular expression implementation. .NET has standard implementation of them

Categories