-2

i try to write a regular expression. Considers this string [converter:mystringornotmystring] I want get mystringornotmystring

See my bad code

regEx = new Regex(@"\[((?:.|\n)*?).\]");
            foreach (Match m in regEx.Matches(stb.ToString()))
            {
                myfunction (m.Value);
            }

[converter:] is keyword

Can you help me and complete my regex please, thanks

1 Answers1

0

Cédirc, It's slightly unclear what you need here, given your comment:

my string can contains a lot of "[converter:xxx]"

However, if we're talking just about a single instance of this string, as per the original question, then the pattern you need is simpler than your initial attempt.

I am assuming that you don't care what the keyword is since you didn't address this in your initial attempt - you only want to pull the 'parameter' from the string.

Basically, what you want is a [ followed by some characters (we don't care what) then a : then some characters (that we want to identify) then a ].

regEx = new Regex(@"\[.*:(.*)\]");
        foreach (Match m in regEx.Matches(stb.ToString()))
        {
            myfunction (m.Value);
        }

The first thing to do (which you tackled correctly) is to match an opening [. This is a special character in RegEx so needs to be escaped - \[.

To identify a single character (when we don't care what the character is) we use a dot (.).

Where we want to identify more than one of something, we have to tell the regex how many - we do this by applying "cardinality". A * indicates zero-or-more, a + indicates one-or-more. There are other more specific ways of stating the number of matches, which I'll leave you to look up. There are also "greedy" and "lazy" versions of cardinality - but let's stick to the problem at hand.

So - .* means zero-or-more characters. And \[.* means a [ followed by zero-or-more characters.

We then specify the :. This is a specific character to match.

So - [\.*: means a [ followed by zero-or-more characters and then a :.

This is easy, right?

Now to complete the pattern we want another set of zero-or-more characters and a closing ] (which we escape).

\[.*:.*\]

We use brackets () to surround a group we want to "capture". In this instance, we only want to capture the second set of zero-or-more characters:

\[.*:(.*)\]

And there you have it.

Check out the link that L.Gutgart left you - it has lots of information that you may find useful in future.

You can also test your patterns at sites such as http://regexstorm.net/tester.

Brett
  • 1,352
  • 8
  • 13