I would like to do something like the below but throw an exception because there is no match. Is that possible?
var val = Regex.Match("nomatchplz", "notgoingtomatch(.*)").Groups[1].Value;
The Regex.Match function returns a Match object. It has the functionality you're looking for. But you should throw the exception yourself
Match x = Regex.Match("","");
if (!x.Success)
{
throw new Exception("My message");
}
Doesn't .Value already throw a NullReferenceException because Group[1] is false? Or is Group[1] already cause an ArgumentOutOfRangeException because the Indexer can't be resolved?
The easiest way is to check the result of the regex and throw if no matches are found. Unless I'm misunderstanding?
Related
In C# 6.0, string interpolations are added.
string myString = $"Value is {someValue}";
How are null values handled in the above example? (if someValue is null)
EDIT:
Just to clarify, I have tested and am aware that it didn't fail, the question was opened to identify whether there are any cases to be aware of, where I'd have to check for nulls before using string interpolation.
That's just the same as string.Format("Value is {0}", someValue) which will check for a null reference and replace it with an empty string. It will however throw an exception if you actually pass null like this string.Format("Value is {0}", null). However in the case of $"Value is {null}" that null is set to an argument first and will not throw.
From TryRoslyn, it's decompiled as;
string arg = null;
string.Format("Value is {0}", arg);
and String.Format will use empty string for null values. In The Format method in brief section;
If the value of the argument is null, the format item is replaced with
String.Empty.
It seems that the behavior depends on which underlying formatting methods are called, and the implementation of these can change over time. If you get a null formated into the string such as "(null)", it is not sure this will stay the same over several years. In some newer version of .NET it can start throwing an exception.
So I think the most safe approach is to make some condition to avoid using the null. Write a simple ternary operation like:
int? someValue = 5;
var valueStr = (someValue is not null) ? someValue.ToString() : string.Empty;
var myString = $"Value is {valueStr}";
It is an extra line of code, but at least the behavior is controlled.
I'm trying to validate a textbox to check that it has a phone number type value entered.
The problem I'm having is that even when the entry is for example: "blah" in these text boxes the Regex is still returning false and no error message is shown.
Regex staffNumVal = new Regex(#"^[a-z]+$");
if (staffNumVal.IsMatch(txtStaffHPhone.Text)||(staffNumVal.IsMatch(txtStaffHourRate.Text)))
{
MessageBox.Show("Please enter a numeric value");
}
Is there a better way to do this that I'm missing? Thanks.
Instead of
Regex staffNumVal = new Regex(#"^[a-z]+$");
Use
Regex staffNumVal = new Regex(#"^[0-9]+$");
if (staffNumVal.IsMatch(txtStaffHPhone.Text)||(staffNumVal.IsMatch(txtStaffHourRate.Text)))
{
//Valid
}
else
{
MessageBox.Show("Please enter a numeric value");
}
Regex staffNumVal = new Regex(#"^\d*$");
Try it like so
int value;
if (int.TryParse(txtStaffHPhone.Text, out value))
{
// it's a valid integer
}
Regex regex = new Regex(#"^\d$");
Refer for Details: Regex for numbers only
Your RegEx does not do what you expect it.
I think the '^' is misplaced. It should be: #"[^a-z]+$".
But even that is wrong, since it accepts things like &.
You can test at: http://regexhero.net/tester/
But I think you'll be better served with a MaskedTestBox. Have you tried that?
Import Microsoft.VisualBasic and use it!
if (Microsoft.VisualBasic.Information.IsNumeric("5"))
{
//Do Something
}
I recently bumped into an exception in my code because I was trimming a null string.
I replaced it with the following:
SomeValue = (SomeString ?? "").Trim();
Can this code ever fail?
Thanks.
Note: I know I can add a try/catch; I'm just looking to make this line fail-proof without using a try/catch.
This will not fail (ie. throw a NullReferenceException), assuming SomeString is indeed a string.
You could achieve the same in many ways:
SomeValue = (SomeString == null)?string.Empty:SomeString.Trim();
It's not the way I would have done it, but no, this shouldn't ever fail now.
I'd probably write an extension method that calls trim after checking for null. Something like this:
public static string NullTrim(this String str) {
if(str == null) {
return string.Empty;
}
return str.Trim();
}
This allows all of the following to compile and execute without error:
"".NullTrim();
" test ".NullTrim();
((string)null).NullTrim();
Well if it was failing because of NullReferenceException, then now it will definitely not fail because of that. As for the rest, I cannot say without context.
I have a piece of code in c# that checks, if a value is a valid regex pattern.
Code is straight forward:
try
{
System.Text.RegularExpressions.Regex.IsMatch("", pattern);
}
catch (Exception ex)
{
return "pattern matches must be a valid regex value";
}
I'm trying to test if it works correctly, but I can't find an invalid regex pattern.
Any suggestions?
This is invalid...
[
You can also test the validity of regular expressions in real-time at http://regexhero.net/tester/
By the way, you don't actually have to test the regular expression against a string to see if it's valid. You can simply instantiate a new Regex object and catch the exception.
This is what Regex Hero does to return a detailed error message...
public string GetRegexError(string _regexPattern, RegexOptions _regexOptions)
{
try
{
Regex _regex = new Regex(_regexPattern, _regexOptions);
}
catch (Exception ex)
{
return ex.Message;
}
return "";
}
Try this:
*
BTW, in Java there is a method to compile a string to a pattern and it throws an exception with precise error diagnostic.
Here's an example of a non-correct expression:
[0-9]++
Here's another one. Anything that ends in a single backslash (dangling backslash) is invalid.
BOOM\
If you want to test, if it works properly, you need to test it with valid and invalid patterns, which should be done using a unit test framework like NUnit.
It is also possible to display a more detailed error message, as also proposed in the C# Cookbook; see the chapter 8.3. Verifying the Syntax of a Regular Expression
Here is a simple example class with some test data (also available on .Net Fiddle, where you can run it right away in your browser)
using System;
using System.Text.RegularExpressions;
public class Program
{
public static Boolean validateRegEx(String pattern)
{
if (pattern == null || pattern.Length == 0)
{
System.Console.Out.WriteLine("RegEx '{0}' is NOT valid. The pattern may not be empty or null.", pattern);
return false;
}
try
{
new Regex(pattern);
System.Console.Out.WriteLine("RegEx '{0}' is valid.", pattern);
return true;
}
catch (ArgumentException ex) If
{
System.Console.Out.WriteLine("RegEx '{0}' is NOT valid: {1}", pattern, ex.Message);
return false;
}
}
public static void Main()
{
// Invalid regular expressions:
validateRegEx(""); // The pattern may not be empty or null.
validateRegEx(null); // The pattern may not be empty or null.
validateRegEx("**"); // Quantifier {x,y} following nothing.
validateRegEx("\\"); // Illegal \ at end of pattern.
validateRegEx("AABB???"); // Nested quantifier ?.
validateRegEx("AA(C(B)A"); // Not enough )'s.
validateRegEx("AA(C)B)A"); // Too many )'s.
// Valid regular expressions:
validateRegEx("A"); // 'A' is valid.
validateRegEx(".*ABA.?"); // '.*ABA.?' is valid.
validateRegEx("AB?A"); // 'AB?A' is valid.
validateRegEx("AB*A"); // AB*A' is valid.
validateRegEx("A(BB){1,4}"); // 'A(BB){1,4}' is valid.
// ...
}
}
What is the shorthand equivalent to the following snippent of code?
if (strValue == ""){
throw new Exception("Mandatory 'strValue' parameter empty");
}
It's probably as short as you can get it, barring removal of spaces and braces (and sacrificing readability in the process).
As for correctness... this might be better:
.NET 4.0:
if (string.IsNullOrWhiteSpace(strValue)){
throw new ArgumentException("Mandatory 'strValue' parameter empty");
}
.NET < 4.0:
if (string.IsNullOrEmpty(strValue)){
throw new ArgumentException("Mandatory 'strValue' parameter empty");
}
Also note that it is bad practice to simply throw Exception - it is much better to select an appropriate exception class from the BCL if one exists, or a custom one if one doesn't. (thanks #djacobson)
if(strValue=="")throw new Exception("Mandatory 'strValue' parameter empty");
All you can do is remove the braces and spaces :)
With a null check, which I think you want, and using ArgumentException:
ThrowIfNullOrEmpty(strValue, "strValue");
...
private void ThrowIfNullOrEmpty(string parameterValue, string parameterName)
{
if String.IsNullorEmpty(parameterValue)
{
throw new ArgumentException("Mandatory 'strValue' parameter empty",
parameterName);
}
}
Obviously only useful if you're doing this more than a few times.
You could use Code Contracts.
You could also use string.IsNullOrWhitespace()
Contract.Requires(string.IsNullOrEmpty(strValue), "** fancy localized message here ***");
It's already short. Instead of doing strValue == "", I'd do String.Empty or String.NullOrEmpty, I can't remember which one is available in .NET
Does not get much shorter, but if want less lines then:
if (String.IsNullOrWhitespace(strValue)) throw new Exception("Mandatory 'strValue' parameter empty");
You're pretty much as short as you can get. I recommend using the IsNullOrEmpty String function for checking for an empty string. Also, it may be suitable to be more specific in your exception handling and throw an ArgumentException.
if (String.IsNullOrEmpty(strValue)) { throw new ArgumentException("strValue must not be null or empty") };
Assuming that you're trying to write more defensive code, you could use Trace.Assert
Trace.Assert(strValue != "", "Mandatory 'strValue' parameter is not empty");
Or you could use the Fluent Validation library to encapsulate more complicated validation.