String.Remove throws ArgumentOutOfRangeException [duplicate] - c#

This question already has answers here:
Remove characters from C# string
(22 answers)
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 1 year ago.
My code is parsing a text file, looking for ID numbers that match the pattern "####-####-#". Once I find a number that matches this pattern, I need to strip out the dashes and store it in a string variable. I'm trying to use String.Remove to remove this character, but keep getting the OutOfRangeException for some reason.
Here's my code:
//regex for the ID number pattern
Regex pattern = new Regex("^[0-9]{4}-[0-9]{4}-[0-9]{1}$");
//StreamReader to iterate thru the file line-by-line
using (StreamReader reader = new StreamReader(pathToMyFile))
{
while (!reader.EndOfStream)
{
readLine = reader.ReadLine();
//the number I want is always at the beginning of the line, so I capture the
//first 11 characters for regex comparison
string possibleMatch = readLine.Substring(0, 11);
if (!String.IsNullOrEmpty(possibleMatch) &&
pattern.Match(possibleMatch).Success)
{
//If possibleMatch isn't blank, and matches the regex, we found an ID
string match = possibleMatch.Remove('-');
}
}
}
When I try to remove the dashes, I get this error:
System.ArgumentOutOfRangeException: 'startIndex must be less than length of string.
Parameter name: startIndex'
The error is always thrown on the possibleMatch.Remove('-') method, never on readLine.Substring(0, 11). Any advice is appreciated.

Related

get the characters before and after certain character having variable length [duplicate]

This question already has answers here:
Split string and get Second value only
(5 answers)
Closed 3 years ago.
I am trying to get the characters that appear before and after certain character ("-").
string val = "7896-2-5";
7896-2-5 here I want to get the character that appear between the two dashes i.e. 2
string val = "4512-12-5";
4512-12-5 so here 12,
the position of first appearance of - is fixed from left side but the position of second appearance of - is determined by the character in between the two - , may be single digit or double digit number.
How can I get the characters?
Easiest would be to use string.Split('-')
e.g.
var middleDigit = string.Split('-')[1];
if your string should have tow dashes try this:
string myString = "4512-12-5";
string result="";
if(myString.Count(f => f =='-') == 2)
result = myString.Substring(myString.IndexOf('-') + 1 ,myString.LastIndexOf('-') - myString.IndexOf('-') - 1);
else
result = "string is not well formated";
Console.WriteLine(result);

Get value between parentheses [duplicate]

This question already has answers here:
How do I extract text that lies between parentheses (round brackets)?
(19 answers)
Closed 4 years ago.
I need to get the all strings that sit between open and closed parentheses. An example string is as follows
[CDATA[[(MyTag),xi(Tag2) ]OT(OurTag3).
The output needs to be an array with MyTag, Tag2, OurTag3 i.e. The strings need to have the parentheses removed.
The code below works but retains the parentheses. How do I adjust the regex pattern to remove the parentheses from the output?
string pattern = #"\(([^)]*)\)";
string MyString = "[CDATA[[(MyTag),xi(Tag2) ]OT(OurTag3)";
Regex re = new Regex(pattern);
foreach (Match match in re.Matches(MyString))
{
Console.WriteLine(match.Groups[1]); // print the captured group 1
}
You should be able to use the following:
(?<=\().+?(?=\))
(?<=() - positive lookbehind for (
.*? - non greedy match for the content
(?=)) - positive lookahead for )

C# Regular Expression For Specific Characters [duplicate]

This question already has answers here:
regex 'literal' meaning in regex
(1 answer)
How to make a regex match case insensitive?
(1 answer)
Closed 4 years ago.
I need to build regex dynamically, so I pass to my method a string of valid characters. Then I use that string to build regex in my method
string valid = "^m><"; // Note 1st char is ^ (special char)
string input = ...; //some string I want to check
Check(valid);
public void Check(string valid)
{
Regex reg = new Regex("[^" + valid + "]");
if (reg.Match(input).ToString().Length > 0)
{
throw new Exception(...);
}
}
I want above Match to throw exception if it finds any other character than characters provided by valid string above. But in my case, even if I dont have any other character tahn these 3, Check method still throws new exception.
What is wrong with this regex?
this resolved it, thanks to everyone for help
Regex reg = new Regex("[^" + valid + "]", RegexOptions.IgnoreCase);

Check the scanned input value is only numbers in C# [duplicate]

This question already has answers here:
Identify if a string is a number
(26 answers)
Closed 6 years ago.
else if (vReadData.Length==14 && vReadData Is Numeric)
{
if (txtIPLoad_MHEBarcode1.Text == "")
{
txtIPLoad_MISBarcode1.Text = vReadData;
txtIPLoad_MHEBarcode1.Focus();
}
else
{
txtIPLoad_MISBarcode2.Text = vReadData;
txtIPLoad_MHEBarcode2.Focus();
}
mMessage("Scan", "Please scan the MHE Barcode!");
return;
}
This is my code for validating a Textbox. I check the condition that the length should be 14 chars. I must also check that the input which comes in variable vReadData must be numeric (only numbers).
Please help me solve this.
I have tried using
else if (Int64.TryParse(vReadData, out num))
but this is not helping me.
Are you looking for a regular expression?
else if (Regex.IsMatch(vReadData, #"^[0-9]{14}$")) {
// vReadData is a string of exactly 14 digits [0..9]
}
Explanation: we have to match two conditions
The string should be exactly 14 characters long
It should be a valid (non-negative) number (I doubt if any negative bar code exits)
After combining both conditions into one we can say that we're looking for a string which consist of 14 digits [0-9] (please notice, that we want [0-9] not \d, since \d in .Net means any digit, including, say Persian ones)
Tests:
string vReadData = #"B2MX15235687CC";
// vReadData = #"12345678901234";
if (Regex.IsMatch(vReadData, #"^[0-9]{14}$"))
Console.Write("Valid");
else
Console.Write("InValid");
Outcome:
InValid
If you uncomment the line you'll get
Valid

Replace text place holders with Regular Expression [duplicate]

This question already has answers here:
Extract string between braces using RegEx, ie {{content}}
(3 answers)
Closed 6 years ago.
I have a text template that has text variables wrapped with {{ and }}.
I need a regular expression to gives me all the matches that "Include {{ and }}".
For example if I have {{FirstName}} in my text I want to get {{FirstName}} back as a match to be able to replace it with the actual variable.
I already found a regular expression that probably gives me what is INSIDE { and } but I don't know how can I modify it to return what I want.
/\{([^)]+)\}/
This pattern should do the trick:
string str = "{{FirstName}} {{LastName}}";
Regex rgx = new Regex("{{.*?}}");
foreach (var match in rgx.Matches(str))
{
// {{FirstName}}
// {{LastName}}
}
Maybe:
alert(/^\{{2}[\w|\s]+\}{2}$/.test('{{FirstName}}'))
^: In the beginning.
$: In the end.
\{{2}: Character { 2 times.
[\w|\s]+: Alphabet characters or whitespace 1 or more times.
\}{2}: Character } 2 times.
UPDATE:
alert(/(^\{{2})?[\w|\s]+(\}{2})?$/.test('FirstName'))

Categories