Detecting whitespace in textbox - c#

In a WinForms textbox with multiple whitespaces (e.g. 1 1 A), where, between the 1s, there is whitespace, how could I detect this via the string methods or regex?

use IndexOf
if( "1 1a".IndexOf(' ') >= 0 ) {
// there is a space.
}

This function should do the trick for you.
bool DoesContainsWhitespace()
{
return textbox1.Text.Contains(" ");
}

int NumberOfWhiteSpaceOccurances(string textFromTextBox){
char[] textHolder = textFromTextBox.toCharArray();
int numberOfWhiteSpaceOccurances = 0;
for(int index= 0; index < textHolder.length; index++){
if(textHolder[index] == ' ')numberOfWhiteSpaceOccurances++;
}
return numberOfWhiteSpaceOccurances;
}

Not pretty clear what the problem is, but in case you just want a way to tell if there is a white space anywhere in a given string, a different solution to the ones proposed by the other stack users (which also work) is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Testing
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(PatternFound("1 1 a"));
Console.WriteLine(PatternFound("1 1 a"));
Console.WriteLine(PatternFound(" 1 1 a"));
}
static bool PatternFound(string str)
{
Regex regEx = new Regex("\\s");
Match match = regEx.Match(str);
return match.Success;
}
}
}
in case what you want is determining whether a given succession of consecutive white spaces appear, then you will need to add more to the regex pattern string.
Refer to http://msdn.microsoft.com/en-us/library/az24scfc(v=vs.110).aspx for the options.

Related

Find exact substring in string array using LINQ in C#

I'm trying to see if an exact substring exists in a string array. It is returning true if the substring exists in the string but it will contains spelling errors.
EDIT:
For example if I am checking if 'Connecticut' exists in the string array but it is spelled 'Connecticute' it will still return true but I do not want it to. I want it to return false for 'Connecticute' and return true for
'Connecticut' only
Is there a way to do this using LINQ?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string[] sample = File.ReadAllLines(#"C:\samplefile.txt");
/* Sample file containing data organised like
Niall Gleeson 123 Fake Street UNIT 63 Connecticute 00703 USA
*/
string[] states = File.ReadAllLines(#"C:\states.txt"); //Text file containing list of all US states
foreach (string s in sample)
{
if (states.Any(s.Contains))
{
Console.WriteLine("Found State");
Console.WriteLine(s);
Console.ReadLine();
}
else
{
Console.WriteLine("Could not find State");
Console.WriteLine(s);
Console.ReadLine();
}
}
}
}
}
String.Contains returns true if one part of the string is anywhere within the string being matched.
Hence "Conneticute".Contains("Conneticut") will be true.
If you want exact matches, what you're looking for is String.Equals
...
if (states.Any(s.Equals))
...
You could use \b to match word breaking characters (ie. white spaces, periods, start or end of string etc):
var r = new Regex("\bConneticut\b", RegexOptions.IgnoreCase);
var m = r.Match("Conneticute");
Console.WriteLine(m.Success); // false
Rather than using string.Contains, which matches whether the string contains the sequence of letters, use a regular expression match, with whatever you consider to be appropriate. For example, this will match on word boundaries,
var x = new [] { "Connect", "Connecticute is a cute place", "Connecticut", "Connecticut is a nice place" };
x.Dump();
var p = new Regex(#"\bConnecticut\b", RegexOptions.Compiled);
x.Where(s=>p.IsMatch(s)).Dump();
This will match "Connecticut" and "CConnecticut is a nice place" but not the other strings. Change the regex to suit your exact requirements.
(.Dump() is used in linqpad, which can be used to experiment with this sort of thing )

How to check if there is a character between two spaces C#

I have a string and want to check if there is a letter(only one) that is surrounded by spaces. I tried using Regex but something is not right.
Console.Write("Write a string: ");
string s = Console.ReadLine();
string[] results = Regex.Matches(s, #" (a-zA-Z) ")
.Cast<Match>()
.Select(m => m.Groups[1].Value)
.ToArray();
I am not sure if I am doing this right I am new to C#
A full blown RegEx seems to be heavy stuff for such a simple operation.
This is a sample how to do it. It does include a lot of assumptions that might not be true for you (the fact that I don't consider start or end of string a valid whitespace, the fact I check for WhiteSpace instead of blank, you will have to check those assumptions I made).
namespace ConsoleApplication4
{
using System;
using System.Collections.Generic;
using System.Linq;
public static class StringExtensions
{
public static IEnumerable<int> IndexOfSingleLetterBetweenWhiteSpace(this string text)
{
return Enumerable.Range(1, text.Length-2)
.Where(index => char.IsLetter(text[index])
&& char.IsWhiteSpace(text[index + 1])
&& char.IsWhiteSpace(text[index - 1]));
}
}
class Program
{
static void Main()
{
var text = "This is a test";
var index = text.IndexOfSingleLetterBetweenWhiteSpace().Single();
Console.WriteLine("There is a single letter '{0}' at index {1}", text[index], index);
Console.ReadLine();
}
}
}
This should print
There is a single letter 'a' at index 8

Not able to get specific pattern inside a string

I want to find a specific pattern of substring inside a string .Upto some extent I can able to get but not exactly what i want to extract .
I am working on a console application . Below i have mentioned the code
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string item = #"wewe=23213123i18n("""", test. ),cstr(12),i18n("""",test3)hdsghwgdhwsgd)";
item = #"MsgBox(I18N(CStr(539)," + "Cannot migrate to the same panel type.)" +", MsgBoxStyle.Exclamation, DOWNLOAD_CAPTION)";
string reg1 = #"i18n(.*),(.*)\)";
string strVal = Regex.Match(item, reg1, RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase).Groups[0].Value;
List<string> str = new List<string> ();
str.Add(strVal);
System.IO.File.WriteAllLines(#"C:\Users\E543925.PACRIM1\Desktop\Tools\Test.txt", str);
}
}
}
Expected output - I18N(CStr(539)," + "Cannot migrate to the same panel type.)
Actual output - I18N(CStr(539),Cannot migrate to the samepaneltype.),MsgBoxStyle.Exclamation, DOWNLOAD_CAPTION)
I have to do some changes in regex expression . i tried , but not able to get success .
I am new to regex and c# .
Please help .
Thanks in advance ..
You want to make the .* lazy (i.e. match as few characters as possible) with .*?
(or perhaps make your regex something like"i18n\([^,)]*,[^)]*\)" instead).
If you want multiple matches, so you should probably have a while-loop.
This:
string item = #"wewe=23213123i18n("""", test. ),cstr(12),i18n("""",test3)hdsghwgdhwsgd)";
item = #"MsgBox(I18N(CStr(539)," + "Cannot migrate to the same panel type.)" +", MsgBoxStyle.Exclamation, DOWNLOAD_CAPTION)";
string reg1 = #"i18n(.*?),(.*?)\)";
Match match = Regex.Match(item, reg1, RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase);
while (match.Success)
{
string strVal = match.Groups[0].Value;
Console.WriteLine(strVal);
match = match.NextMatch();
}
Prints:
I18N(CStr(539),Cannot migrate to the same panel type.)
Live demo.
you can try this regex:
i18n(\([^\)]*\))
it means: match i18n and capture groups that start with an open (, are followed by any character except a closed ) and then have a closed )

C# Regex Validating Mac Address

I am trying to validate mac addresses. In this instance there is no - or : for example a valid mac would be either:
0000000000
00-00-00-00-00-00
00:00:00:00:00:00
However I keep getting false when run against the below code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace parsingxml
{
class Program
{
static void Main(string[] args)
{
Console.Write("Give me a mac address: ");
string input = Console.ReadLine();
input = input.Replace(" ", "").Replace(":","").Replace("-","");
Regex r = new Regex("^([:xdigit:]){12}$");
if (r.IsMatch(input))
{
Console.Write("Valid Mac");
}
else
{
Console.Write("Invalid Mac");
}
Console.Read();
}
}
}
OUTPUT: Invalid Mac
.NET regex does not have support for POSIX character class. And even if it does support, you need to enclose it in [] to make it effective, i.e. [[:xdigit:]], otherwise, it will be treated as a character class with the characters :, x, d, i, g, t.
You probably want this regex instead (for the MAC address after you have cleaned up the unwanted characters):
^[a-fA-F0-9]{12}$
Note that by cleaning up the string of space, - and :, you will allow inputs as shown below to pass:
34: 3-342-9fbc: 6:7
DEMO
Try this regex instead:
^(?:[0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}|(?:[0-9a-fA-F]{2}-){5}[0-9a-fA-F]{2}|(?:[0-9a-fA-F]{2}){5}[0-9a-fA-F]{2}$
Matches:
12-23-34-45-56-67
12:23:34:45:56:67
122334455667
But not:
12:34-4556-67
Edit: Your code works for me.
Seems like you could just do this:
Regex r = new Regex("^([0-9a-fA-F]{2}(?:(?:-[0-9a-fA-F]{2}){5}|(?::[0-9a-fA-F]{2}){5}|[0-9a-fA-F]{10}))$");
Or this, which is a lot simpler and would be a little more forgiving:
Regex r = new Regex("^([0-9a-fA-F]{2}(?:[:-]?[0-9a-fA-F]{2}){5})$");
I'd use a regular expression like this one, myself:
Regex rxMacAddress = new Regex( #"^[0-9a-fA-F]{2}(((:[0-9a-fA-F]{2}){5})|((:[0-9a-fA-F]{2}){5}))$") ;
6 pairs of hex digits, separator either by colons or by hyphens, but not a mixture.
Your regex isn't good. Here you got a good one:
public const string ValidatorInvalidMacAddress = "^([0-9A-Fa-f]{2}[:-]?){5}([0-9A-Fa-f]{2})$";
Correct Regex expression that worked for me and accept either macaddress with either all - or all : separation is :- "^[0-9a-fA-F]{2}(((:[0-9a-fA-F]{2}){5})|((-[0-9a-fA-F]{2}){5}))$"
using System.Net.NetworkInformation;
try{
PhysicalAddress py = PhysicalAddress.Parse("abcd");
}catch(Exception){
Console.WriteLine("Mac address not valid");
}

String normalisation

I'm writing some code which needs to do string normalisation, I want to turn a given string into a camel-case representation (well, to the best guess at least). Example:
"the quick brown fox" => "TheQuickBrownFox"
"the_quick_brown_fox" => "TheQuickBrownFox"
"123The_quIck bROWN FOX" => "TheQuickBrownFox"
"the_quick brown fox 123" => "TheQuickBrownFox123"
"thequickbrownfox" => "Thequickbrownfox"
I think you should be able to get the idea from those examples. I want to strip out all special characters (', ", !, #, ., etc), capitalise every word (words are defined by a space, _ or -) and any leading numbers dropped (trailing/ internal are ok, but this requirement isn't vital, depending on the difficulty really).
I'm trying to work out what would be the best way to achieve this. My first guess would be with a regular expression, but my regex skills are bad at best so I wouldn't really know where to start.
My other idea would be to loop and parse the data, say break it down into words, parse each one, and rebuilt the string that way.
Or is there another way in which I could go about it?
How about a simple solution using Strings.StrConv in the Microsoft.VisualBasic namespace?
(Don't forget to add a Project Reference to Microsoft.VisualBasic):
using System;
using VB = Microsoft.VisualBasic;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(VB.Strings.StrConv("QUICK BROWN", VB.VbStrConv.ProperCase, 0));
Console.ReadLine();
}
}
}
This regex matches all words. Then, we Aggregate them with a method that capitalizes the first chars, and ToLowers the rest of the string.
Regex regex = new Regex(#"[a-zA-Z]*", RegexOptions.Compiled);
private string CamelCase(string str)
{
return regex.Matches(str).OfType<Match>().Aggregate("", (s, match) => s + CamelWord(match.Value));
}
private string CamelWord(string word)
{
if (string.IsNullOrEmpty(word))
return "";
return char.ToUpper(word[0]) + word.Substring(1).ToLower();
}
This method ignores numbers, by the way. To Add them, you can change the regex to #"[a-zA-Z]*|[0-9]*", I suppose - but I haven't tested it.
Any solution that involves matching particular characters may not work well with some character encodings, particularly if Unicode representation is being used, which has dozens of space characters, thousands of 'symbols', thousands of punctuation characters, thousands of 'letters', etc. It would be better where-ever possible to use built-in Unicode-aware functions. In terms of what is a 'special character', well you could decide based on Unicode categories. For instance, it would include 'Punctuation' but would it include 'Symbols'?
ToLower(), IsLetter(), etc should be fine, and take into account all possible letters in Unicode. Matching against dashes and slashes should probably take into account some of the dozens of space and dash characters in Unicode.
You could wear ruby slippers to work :)
def camelize str
str.gsub(/^[^a-zA-z]*/, '').split(/[^a-zA-Z0-9]/).map(&:capitalize).join
end
thought it'd be fun to try it, here's what i came up with:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder();
string sentence = "123The_quIck bROWN FOX1234";
sentence = sentence.ToLower();
char[] s = sentence.ToCharArray();
bool atStart = true;
char pChar = ' ';
char[] spaces = { ' ', '_', '-' };
char a;
foreach (char c in s)
{
if (atStart && char.IsDigit(c)) continue;
if (char.IsLetter(c))
{
a = c;
if (spaces.Contains(pChar))
a = char.ToUpper(a);
sb.Append(a);
atStart = false;
}
else if(char.IsDigit(c))
{
sb.Append(c);
}
pChar = c;
}
Console.WriteLine(sb.ToString());
Console.ReadLine();
}
}
}

Categories

Resources