6

Okay, lets say I have a string "The cat in the hat dog", and I know want to regex match cat and dog from the same string.

So I have something like:

Dim myString As String = "The cat in the hat dog"
Dim regex = New Regex("\bcat\b.*\bdog")
Dim match = regex.Match(myString)
If match.Success Then
    Console.WriteLine(match.Value)
End If

The match.Value returns "cat in the hat dog", which is expected.

But what I really need is to just "cat dog" without the other words in the middle, and I'm stuck.

Thanks for any help!

If it helps, the string I'm trying to parse is something like "Game Name 20_03 Starter Pack r6" and I'm trying to pull "20_03 r6" out as version information. Currently using "\b\d{2}_\d{2}\b.\br\d" as my regex string.

2 Answers 2

9

You can parenthesize parts of your regular expression to create groups that capture values:

Dim regex As New Regex("\b(cat)\b.*\b(dog)")

Then use match.Groups(1).Value and match.Groups(2).Value.

Sign up to request clarification or add additional context in comments.

Comments

5

Your regex would be,

Dim regex = New Regex("\bcat\b|\bdog\b")

This matches the string cat or dog in the input string.

DEMO

For the second string, your regex would be

\b\d{2}_\d{2}\b|r\d

DEMO

Explanation:

  • \b Matches the word boundary(ie, matches between a word character and a non-word character).
  • \d{2} Matches exactly a two digit number.
  • _ Matches a literal underscore symbol.
  • \d{2} Matches exactly a two digit number.
  • \b Matches the word boundary(ie, matches between a word character and a non-word character).
  • | Logical OR operator usually used to combine two regex patterns.this|that, this or that.
  • r\d Literal r followed by a single digit.

2 Comments

Could you people post the reason for downvote? I have to learn something.
Ooh, that regex test site is nice. I don't think the logical OR gate is exactly what I need though since I don't have control over the string and it can be changed by the end user. I only want to pull the version information from it if both pieces are present. Should have clarified more. Using the other guy's solution, but I appreciate your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.