Daniel Martin
Daniel Martin

Reputation: 570

Regex to filter out $

I have a powershell script that returns the following items:

migration test 
TECHS-NT$
Administrator 
krbtgt
SDI$

Now, I want to eliminate the items that contain a $ and feed the items that do not have a $ into a list. Something like,

    List<string> powershellResults = new List<string>();
    foreach (string str in Powershell.Create().AddScript(PS Script))
    {
        if (Regex.IsMatch(str, @"(\w*[^$])"))
        {
            powershellResults.Add(str);
       }
    }

    foreach (string str in powershellResults)
    {
        Console.WriteLine(str);
    }

But, (\w*[^$]) matches every item instead of filtering out the SDI$ and TECHS-NT$ items. What should my regex look like, if not (\w*[^$]) ?

Upvotes: 1

Views: 74

Answers (3)

Chris
Chris

Reputation: 5514

Your regex looks a bit weird. If you want to match lines ending with a dollar sign, try something like this:

\$$

Remember that $ means end of line/string in a regex, so to use it it needs to be escaped. If you wish to match any line containg a dollar sign, simply:

\$

Though, if we could convince you not to use a regex for this, LINQ would be alot easier. Simply:

var res = from line in Powershell.Create().AddScript( PS Script )
          where !line.EndsWith( "$" )
          select line;

Or:

var res = Powershell.Create().AddScript( PS Script ).Where( q => !q.EndsWith( "$" ) );

Change EndsWith to Contains to find any dollar sign, not just ones at the end.

Upvotes: 2

prospector
prospector

Reputation: 3469

Regex isn't needed here, use IndexOf which returns -1 when not found.

  if (str.IndexOf("$")==-1)
   {
        powershellResults.Add(str);
   }

Upvotes: 0

Becuzz
Becuzz

Reputation: 6866

Regex is completely unnecessary here. Just use the Contains method to see if the string has a $ in it.

foreach (string str in Powershell.Create().AddScript(PS Script))
{
    if (!str.Contains("$"))
    {
        powershellResults.Add(str);
   }
}

Upvotes: 1

Related Questions