For loop check if string only has 3 capital letters followed by 4 numbers [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I input a string that has to start with three capital letters and ending with four digits (like so: "SJL1036") the program is just supposed to check if my input follows that model.
if i were to input "Sjl1036" og "SJL103" it would output that it is a false statement.

Try this regular expression. 3 uppercase, 4 numbers.
^[A-Z]{3}[0-9]{4}$
For example:
var value = "FSK2526";
if (Regex.IsMatch(value, #"^[A-Z]{3}[0-9]{4}$")) {
// it matches
}

Although you could do it with for loop, but you could simplify it further with regex like:
Regex regex = new Regex(#"^[A-Z]{3}.*[0-9]{4}$");
Match match = regex.Match("SJL1036");
if (match.Success)
{
Console.WriteLine(match.Value);
}

If this is the requirement:
A string that has to start with three capital letters and ending with
four digits
Probably the most efficient approach is using string methods:
bool valid = input.Length >= 7
&& input.Remove(3).All(Char.IsUpper) // or input.Substring(0, 3)
&& input.Substring(input.Length - 4).All(Char.IsDigit);
If the actual requirement is "3 capital letters followed by 4 numbers"(so 7 characters) you just need to change input.Length >= 7 to input.Length == 7.

A non-Regex option, You can use a bit of LINQ like:
string str = "SJL1036";
if (str.Length == 7 &&
str.Take(3).All(char.IsUpper)
&& str.Skip(3).All(char.IsDigit))
{
Console.WriteLine("valid");
}
else
{
Console.WriteLine("invalid");
}

Related

Splitting a string into characters, but keeping some together [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I have this string: TF'E'
I want to split it to characters, but the '" character should join the character before it.
So it would look like this: T, F' and E'
You could use a regular expression to split the string at each position immediately before a new letter and an optional ':
var input = "TF'E'";
var output = Regex.Split(input, #"(?<!^)(?=\p{L}'?)");
output will now be a string array like ["T", "F'", "E'"]. The lookbehind (?<!^) ensure we never split at the start of the string, whereas the lookahead (?=\p{L}'?) describes one letter \p{L} followed by 0 or 1 '.
You can use a regex to capture "an uppercase character followed optionally by an apostrophe"
var mc = Regex.Matches(input, "(?<x>[A-Z]'?)");
foreach(Match m in mc)
Console.WriteLine(m.Groups["x"].Value);
If you don't like regex, you can use this method:
public static IEnumerable<string> Split(string input)
{
for(int i = 0; i < input.Length; i++)
{
if(i != (input.Length - 1) && input[i+1] == '\'')
{
yield return input[i].ToString() + input[i+1].ToString();
i++;
}
else
{
yield return input[i].ToString();
}
}
}
We loop through the input string. We check if there is a next character and if it is a '. If true, return the current character and the next character and increase the index by one. If false, just return the current character.
Online demo: https://dotnetfiddle.net/sPCftB

How to validate a 5 characters input of textbox that the first 3 characters to letters only and the last 2 characters to numbers c# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I need to create a method that checks a textbox 5 character inputs. The first 3 characters should be letters and the last 2 characters should be numbers.
here's my current code:
public void checkInput(String s) {
if (CheckInputString(s)) {
//To Check if the first 3 characters are letters and check last 2 characters if numbers
}
else {
//Invalid
}
please help.
You can use RegEx
[A-Za-z]{3} - Matches 3 alpha
[0-9]{2} - Matches 2 numbers
Test your inputs with given regex online https://regex101.com/r/fF4zG9/5
Regex temp = new Regex("^[A-Za-z]{3}[0-9]{2}$");
string yourVal = "asd12";
if(temp.IsMatch(yourVal))
{
//Matches
}
else
{
//Fails
}
You can use a regular expression to check the string.
^[a-zA-Z]{3}[0-9]{2}$
Your code could look like this:
public bool CheckInputString(string s)
{
System.Text.Regex regex = new System.Text.Regex("^[a-zA-Z]{3}[0-9]{2}$");
return regex.IsMatch(s);
}
One way to do it is to simply validate each requirement on the string and then return true if they all pass.
public static bool IsValid(string input)
{
return input != null && // Not null
input.Length == 5 && // Is 5 characters
input.Take(3).All(char.IsLetter) && // First three are letters
input.Skip(3).All(char.IsDigit); // The rest are numbers
}

How do I remove an X number of capital letters from a string? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I want to remove an X number of capital letters from a string.
For example if I had the strings:
string Line1 = "NICEWEather";
and
string Line2 = "HAPpyhour";
How would I create a function that pulls out the 2 sets of Capital letters?
Try using regular expressions with \p{Lu} for a Unicode capital letter
using System.Text.RegularExpressions;
...
// Let's remove 2 or more consequent capital letters
int X = 2;
// English and Russian
string source = "NICEWEather - ХОРОшая ПОГОда - Keep It (HAPpyhour)";
// ather - шая да - Keep It (pyhour)
string result = Regex.Replace(source, #"\p{Lu}{" + X.ToString() + ",}", "");
Here we use \p{Lu}{2,} pattern: capital letter appeared X (2 in the code above) or more times.
To remove capital letter from string
string str = " NICEWEather";
Regex pattern = new Regex("[^a-z]");
string result = pattern.Replace(str, "");
Console.WriteLine(result );
output: ather
to remove capital letter if occurrences more than once in sequence order then try this
string str = " NICEWEather";
Regex pattern = new Regex(#"\p{Lu}{2,}");
string output = pattern.Replace(str, "");
Console.WriteLine(output);

Match the number of commas in CSV line that are not between quotation marks with C# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a CSV line and I need to count the number of columns in the line.
Some of the column values contains comma (in this case the value will be surround with quotation marks)
I need a Regex that will match only commas that are not surrounded with quotation marks.
For example:
a,b,c
will match 2 commas
and The line:
a,"b,c",d,"e,f"
will match 3 commas
Thanks,
Nadav.
I doubt if a complex regular expression will be better than an easy loop:
private static int CountCommas(String source, Char separator = ',') {
int result = 0;
Boolean inQuotation = false;
foreach (Char c in source)
if (c == '"')
inQuotation = !inQuotation;
else if ((c == separator) && !inQuotation)
result += 1;
return result;
}
Test
// 3
Console.Write(CountCommas("a, \"b,c\", d, \"e,f\""));

How to remove extra hyphens from string in c#? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a string in which spaces are replaced by hyphen i.e '-' if there multiple hyphens then I want to remove all but one from the string. Only hyphens must be removed; not numbers that are consecutive.
Eg: --11- must be -11- and not -1-
Eg: --12- o/p: -12-
Eg: -12-- o/p: -12-
using Linq or a string function in C#.
I have tried it using str = str.Remove(str.Length - 1);, but it only removes one character.
If you just want to collapse multiple consecutive - characters into one, you could easily do this using regex:
string output = Regex.Replace(input, #"\-+", "-");
try
string sample = "--12";
string Reqdoutput = sample.Replace("--", "-");
If you want to replace just the hyphen, you can do one of the things given in the other answers. For removing all double characters, you can do this:
String input = "------hello-----";
int i = 1;
while (i < input.Length)
{
if (input[i] == input[i - 1])
{
input = input.Remove(i, 1);
}
else
{
i++;
}
}
Console.WriteLine(input); // Will give "-helo-"
Why not just do :
yourString = yourString.Replace("--", "-");
Or did I understand the problem wrong ?

Categories