I need to check if a string has at least two alpha characters, like a1763r or ab1244
I was thinking I would use something like:
myString = "a123B";
myString.Any(char.IsDigit).Count();
but I'm using .net 2.0 so this method Any() does not exists.
Is there something equivalent?
Don't know about alpha or what not, but you can count how many characters are digits without Linq like so:
string str = "a123B";
int digits = 0;
foreach (char c in str)
if (char.IsDigit(c))
digits++;
print(digits); // 3
You can create a simple helper function that loops over your string, taking in a minimum threshold to meet. It returns boolean to match the type of output behavior from .Any()
public bool ContainsMinAlphaCharacters(string input, int threshold)
{
var count = 0;
foreach (var character in input)
{
if (char.IsDigit(character)) count++;
if (count >= threshold)
{
return true;
}
}
return false;
}
Use regexpressions
two letters: Regex.IsMatch(myString, "[A-Za-z].*?[A-Za-z]");
two digits: Regex.IsMatch(myString, "\d.*?\d");
Not really. You will have to loop through the string and check if each character is a digit to get the count.
Related
My reference number is "DTS00001" it is a String variable in C# program
i want to increment this number by one and the result should be like "DTS00002"
here is the code i tried,
while (reader.Read())
{
String str = reader["rfno"].ToString();
String st = str.Substring(3, 5);
int number = Convert.ToInt32(st);
number += 1;
string myNewString = "DTS" + number;
MessageBox.Show(myNewString);
The result doesn't contain the required leading zeros before the new number.
.
Homework or not, here's one way to do it. It's heavily influensed by stemas answer. It uses Regex to split the alphabetical from the numeric. And PadLeft to maintain the right number of leading zeroes.
Tim Schmelters answer is much more elegant, but this will work for other types of product-numbers as well, and is not limited to a specific number of leading zeros or a specific character set in the beginning. The downside with this solution is that it has to be [alphabetical][numerical].
private static string Increase(string productNo)
{
// This is a regex to split it into to groups.
var numAlpha = new Regex("(?<Alpha>[a-zA-Z]*[ _]?)(?<Numeric>[0-9]*)");
// Match the input string for the regex.
var match = numAlpha.Match(productNo);
// Get the alphabetical part.
var alpha = match.Groups["Alpha"].Value;
// Get the numeric part.
int num = int.Parse(match.Groups["Numeric"].Value);
// Add +1
num++;
// Combine the alphabetical part with the increased number, but use PadLeft to maintain the padding (leading zeros).
var newString = string.Format("{0}{1}", alpha, num.ToString().PadLeft(match.Groups["Numeric"].Value.Length, '0'));
return newString;
}
Console.WriteLine(Increase("DTS00008"));
Console.WriteLine(Increase("DTS00010"));
Console.WriteLine(Increase("DTS00020"));
Console.WriteLine(Increase("DTS00099"));
Console.WriteLine(Increase("PRODUCT0000009"));
Console.WriteLine(Increase("PRODUCT0000001"));
Output:
DTS00009
DTS00011
DTS00021
DTS00100
PRODUCT0000010
PRODUCT0000002
I am new to regex stuff in C#. I am not sure how to use the regex to validate client reference number. This client reference number has 3 different types : id, mobile number, and serial number.
C#:
string client = "ABC 1234567891233";
//do code stuff here:
if Regex matches 3-4 digits to client, return value = client id
else if Regex matches 8 digts to client, return value = ref no
else if Regex matches 13 digits to client, return value = phone no
I dont know how to count digits using Regex for different types. Like Regex("{![\d.....}").
I don't understand why you're bent on using regular expressions here. A simple one-liner would do, eg. even such an extension method:
static int NumbersCount(this string str)
{
return str.ToCharArray().Where(c => Char.IsNumber(c)).Count();
}
It's clearer and more maintainable in my opinion.
You could probably give it a go with group matching and something along the lines of
"(?<client>[0-9]{5,9}?)|(?<serial>[0-9]{10}?)|(?<mobile>[0-9]{13,}?)"
Then you'd check whether you have a match for "client", "serial", "mobile" and interpret the string input on that basis. But is it easier to understand?
Does it express your intentions more clearly for those reading your code later on?
If the requirement is such that these numbers must be consecutive (as #Corak points out)... I'd still write that iteratively, like so:
/// <summary>
/// returns lengths of all the numeric sequences encountered in the string
/// </summary>
static IEnumerable<int> Lengths(string str)
{
var count = 0;
for (var i = 0; i < str.Length; i++)
{
if (Char.IsNumber(str[i]))
{
count++;
}
if ((!Char.IsNumber(str[i]) || i == str.Length - 1) && count > 0)
{
yield return count;
count = 0;
}
}
}
And then you could simply:
bool IsClientID(string str)
{
var lenghts = Lengths(str);
return lenghts.Count() == 1 && lenghts.Single() == 5;
}
Is it more verbose? Yes, but chances are that people will still like you more than if you make them fiddling with regex every time the validation rules happen to change, or some debugging is required : ) This includes your future self.
I'm not sure if I understood your question. But if you want to get the number of Numerical Characters from a string you can use the following code:
Regex regex = new Regex(#"^[0-9]+$");
string ValidateString = regex.Replace(ValidateString, "");
if(ValidateString.Length > 4 && ValidateString.Length < 10)
//this is a customer id
....
I'm trying to compare first 3 chars of a string, i'm trying to use substring then compare.
The strings are read from an input file, and the string may not be 3 chars long. if an string is not 3 chars long i want the substring method to replace the empty chars with spaces.
How would i go about doing that.
Current code throws an exeption when the string is not long enough.
Use String.PadRight
myString.PadRight(3, ' ');
// do SubString here..
You could also create a .Left extension method that doesn't throw an exception when the string isn't big enough:
public static string Left(this string s, int len)
{
if (len == 0 || s.Length == 0)
return "";
else if (s.Length <= len)
return s;
else
return s.Substring(0, len);
}
Usage:
myString.Left(3);
Use one of the String.PadRight() methods before calling Substring():
string subString = myString.PadRight(3).Substring(0,3);
If you use the overload with one parameter like I did above, it will insert spaces.
string subString1 = string1.PadRight(3).Substring(0,3);
string subString2 = string2.PadRight(3).Substring(0,3);
if (String.Compare(subString1, subString2) == 0)
{
// if equal
}
else
{
// not equal
}
I used separate variables because it's a bit more readable, but you could in-line them in the if statement if you wanted to.
You can use this dirty hack:
var res = (myStr+" ").Substring(...);
I have strings like this:
var a = "abcdefg";
var b = "xxxxxxxx";
The strings are always longer than five characters.
Now I need to trim off the last 3 characters. Is there some simple way that I can do this with C#?
In the trivial case you can just use
result = s.Substring(0, s.Length-3);
to remove the last three characters from the string.
Or as Jason suggested Remove is an alternative:
result = s.Remove(s.Length-3)
Unfortunately for unicode strings there can be a few problems:
A unicode codepoint can consist of multiple chars since the encoding of string is UTF-16 (See Surrogate pairs). This happens only for characters outside the basic plane, i.e. which have a code-point >2^16. This is relevant if you want to support Chinese.
A glyph (graphical symbol) can consist of multiple codepoints. For example ä can be written as a followed by a combining ¨.
Behavior with right-to-left writing might not be what you want either
You want String.Remove(Int32)
Deletes all the characters from this string beginning at a specified
position and continuing through the last position.
If you want to perform validation, along the lines of druttka's answer, I would suggest creating an extension method
public static class MyStringExtensions
{
public static string SafeRemove(this string s, int numCharactersToRemove)
{
if (numCharactersToRemove > s.Length)
{
throw new ArgumentException("numCharactersToRemove");
}
// other validation here
return s.Remove(s.Length - numCharactersToRemove);
}
}
var s = "123456";
var r = s.SafeRemove(3); //r = "123"
var t = s.SafeRemove(7); //throws ArgumentException
string a = "abcdefg";
a = a.Remove(a.Length - 3);
string newString = oldString.Substring(0, oldString.Length - 4);
If you really only need to trim off the last 3 characters, you can do this
string a = "abcdefg";
if (a.Length > 3)
{
a = a.Substring(0, a.Length-3);
}
else
{
a = String.Empty;
}
I have a string that contains an int. How can I parse the int in C#?
Suppose I have the following strings, which contains an integer:
15 person
person 15
person15
15person
How can I track them, or return null if no integer is found in the string?
You can remove all non-digits, and parse the string if there is anything left:
str = Regex.Replace(str, "\D+", String.Empty);
if (str.Length > 0) {
int value = Int32.Parse(str);
// here you can use the value
}
Paste this code into a test:
public int? ParseAnInt(string s)
{
var match = System.Text.RegularExpressions.Regex.Match(s, #"\d+");
if (match.Success)
{
int result;
//still use TryParse to handle integer overflow
if (int.TryParse(match.Value, out result))
return result;
}
return null;
}
[TestMethod]
public void TestThis()
{
Assert.AreEqual(15, ParseAnInt("15 person"));
Assert.AreEqual(15, ParseAnInt("person 15"));
Assert.AreEqual(15, ParseAnInt("person15"));
Assert.AreEqual(15, ParseAnInt("15person"));
Assert.IsNull(ParseAnInt("nonumber"));
}
The method returns null is no number is found - it also handles the case where the number causes an integer overflow.
To reduce the chance of an overflow you could instead use long.TryParse
Equally if you anticipate multiple groups of digits, and you want to parse each group as a discreet number you could use Regex.Matches - which will return an enumerable of all the matches in the input string.
Use something like this :
Regex r = new Regex("\d+");
Match m = r.Match(yourinputstring);
if(m.Success)
{
Dosomethingwiththevalue(m.Value);
}
Since everyone uses Regex to extract the numbers, here's a Linq way to do it:
string input = "15person";
string numerics = new string(input.Where(Char.IsDigit).ToArray());
int result = int.Parse(numerics);
Just for the sake of completeness, it's probably not overly elegant. Regarding Jaymz' comment, this would return 151314 when 15per13so14n is passed.