-2

I am trying to find the word "Amount" within the following list of words:

WaterAmount 
DamageAmount 
AmountOwed

I tried to use regex, but the following doesn't work:

Regex.IsMatch(name, @"\Amount\")

Can someone please help me to figure out how to do this?

Thank you.

Update:

Code being used:

foreach (string name in Request.Form.AllKeys)
        {

            if (Regex.IsMatch(name, "Amount"))
            {
                Response.Write(Request.Form[name]);
            }
            else
            {
                Response.Write("Not working\n");
            }

        }
}
Plasmarob
  • 1,321
  • 12
  • 20
Brad Hazelnut
  • 1,603
  • 5
  • 21
  • 33

3 Answers3

3

Instead of using regex, use:

name.Contains("Amount")

this should return a boolean as to whether Amount is in the string.

You don't need regex for this situation (and sometimes it's good to go without when unnecessary)

as others suggested,

name.IndexOf("amount", StringComparison.OrdinalIgnoreCase) >= 0;

could also be used to include "AMOUNT", "amount", "AmOunT", etc.

Or:

name.IndexOf("amount", StringComparison.OrdinalIgnoreCase)!= -1

We're just checking that IndexOf doesn't send back -1 for 'not found'.

The reason you might not want to use:

name.ToLower().Contains("amount")

is because it will have problems with international characters (accents, etc). If you were passing in a variable that could have any text, that could pose a problem. For a case with a constant string, it might be fine, however (though not extremely recommended)

Edit:

If I understand C# correctly (not my expertise, though i've used it), this should work:

foreach (string name in Request.Form.AllKeys)
{
    if (name.IndexOf("amount", StringComparison.OrdinalIgnoreCase) >= 0)
    {
        Response.Write(Request.Form[name]);
    }
    else
    {
        Response.Write("Not working\n");
    }
}

I see an extra brace in your code. Is that supposed to be there?

Plasmarob
  • 1,321
  • 12
  • 20
  • 3
    `name.IndexOf("amount", StringComparison.OrdinalIgnoreCase) >= 0` is better for case insensitive `Contains`. Check [this answer](http://stackoverflow.com/a/444818/393487) – Ahmed KRAIEM Nov 20 '13 at 16:22
1

I think your approach is correct. I would suggest one minor change for it to work...

Regex.IsMatch(name, @"Amount")

Good Luck!

gpmurthy
  • 2,397
  • 19
  • 21
0
var index = name.IndexOf("Amount", 0, name.Length);

This will get you the index of the first occurrence. If you want all of them, just loop trough the text.

To ignore case sensitivity;

var index = name.IndexOf("Amount", 0, StringComparison.OrdinalIgnoreCase);

And if there's no match, IndexOf returns -1.

If you just want to know if your string is in there, use .Contains().

Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170