2

I am very inexperienced when it comes to regular expressions. What I'm trying to do is iterate through a list of strings and try to locate strings that are of a certain pattern. The strings I am interested in will be in the form of "some text ***{some text}***" How do I write a RegEx to match up to? I was trying this:

Regex expression = new Regex("***");

but this gives me an error. parsing "***" - Quantifier {x,y} following nothing.

Can someone point me in the right direction?

I'm trying to loop through select list options and add a css class to the options that are relevant.

Regex expression = new Regex("***");
foreach (ListItem li in listItemCollection)
{
    if (expression.IsMatch(li.Value))
        li.Attributes.Add("class", "highlight1");
}

but this obviously isn't working.

Any help is appreciated, ~ck in San Diego

6 Answers 6

9

You need to escape the asterisk, as it's a valid metacharacter in RegExp.

Regex expression = new Regex(@"\*\*\*");
Sign up to request clarification or add additional context in comments.

1 Comment

Regex.Escape is also useful: new Regex(Regex.Escape("***"));
3

If all you're trying to do is match three asterisks, why not just use the string.Contains method instead of a regular expression?

foreach (ListItem li in listItemCollection)
{
    if (li.Value.Contains("***"))
        li.Attributes.Add("class", "highlight1");
}

1 Comment

+1 for thinking about the actual problem instead of just fixing the code. This is a better idea instead of using Regex.
3

* has a special meaning in regular expression.

If you are looking to match 3 asteriks, try

Regex expression = new Regex(@"\*\*\*");

EDIT:

If you are only trying to verify if a string contains "***", look at bdukes' answer.

Comments

2

Try something like this:

\*\*\*[^\*]+\*\*\*

Comments

0

If you are going to test out regexes, get an application for testing. Any of these would be a good start. I've been attached to Chris Sells's tester for a long time but there are lots out there.

Comments

0

You should try this regex pattern

\*{3}\{[^\}]*}\*{3}

This will find ***{some text}***

If you want the text before the * you should use this one

^[\w\s]*\*{3}\{[^\}]*\}\*{3}
  • ^ - beginning of the input
  • [\w\s]* any char in a-z, A-Z, 0-9, _ and white space, 0 or more times
  • \*{3} three asterisks
  • \{ match {
  • [^\}]* any char except } 0 or more times
  • \} match }
  • \*{3} match three asterisks

1 Comment

@Cédric, notice the correction re: \w - it matches digits, too. Also, in some regex flavors \w matches letters and digits from all writing systems, not just the ASCII ones.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.