user2505650
user2505650

Reputation: 1381

Regex , Detect all strings preceded with a certain character

How can I detect in c# all strings that are preceede with '%' or '$' ?

EDIT :

if I have the following string for example :

string  test =   "Shipments will cost $150USD , which representes a rise of %34 ."

How can I detect the $150USD and %34 with regex ?

Upvotes: 1

Views: 464

Answers (2)

Amit Joki
Amit Joki

Reputation: 59232

As simple as this:

string s = "Shipments will cost $150USD , which representes a rise of %34 .";
            var matches = Regex.Matches(s, @"(\$|%)\w+");
            for (int i = 0; i < matches.Count; i++)
            {
                Console.WriteLine(matches[i].Value);
            }

Upvotes: 1

Szymon
Szymon

Reputation: 43023

If you mean finding all words, you can use that regex.

(?<=\s?)[%$]\w+(?=\s?)

So in Shipments will cost $150USD, which representes a rise of %34. it will find $150USD and %34.

The C# code is:

String subjectString = "Shipments will cost $150USD, which representes a rise of %34.";
var matches = Regex.Matches(subjectString, @"(?<=\s?)[%$]\w+(?=\s?)");

foreach (Match match in matches)
{
    var value = match.Value;
}

Upvotes: 1

Related Questions