2

I have strings that follow the format "x Packs of y" so for example "15 packs of 5", "1 pack of 10" and so on.

I would like to use a regex that looks for "x Packs of y" and puts x in one variable and y in a second variable.

Please can somebody advise how I do this?

3 Answers 3

4

Try this...

Dim foo = "15 packs of 5"

Dim match = Regex.Match(foo, "(\d+) packs? of (\d+)", RegexOptions.IgnoreCase)

Dim x = match.Groups(1).Value
Dim y = match.Groups(2).Value

Console.WriteLine("x = " & x)
Console.WriteLine("y = " & y)

Live Demo - Fiddle

Update: Thanks Braj for pointing out the pack/packs.

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

2 Comments

what about this 1 pack of 10
Don;t you think its same that I used.
3

In .NET, for ASCII Digits, use [0-9], not \d

In .NET, \d matches digits in any script, including Thai and Klingon. Assuming you only want ASCII digits 0 through 9 rather than 654۳۲١८৮੪૯୫୬१७੩௮, use this:

Dim firstNumber As String
Dim secondNumber As String
Dim RegexObj As New Regex("([0-9]+) packs? of ([0-9]+)", RegexOptions.IgnoreCase)
firstNumber = RegexObj.Match(yourString).Groups(1).Value
secondNumber = RegexObj.Match(yourString).Groups(2).Value

Explanation

  • RegexOptions.IgnoreCase makes it case-insensitive
  • ([0-9]+) captures one or more digits to Group 1
  • packs? matches pack with an optional s
  • ([0-9]+) captures one or more digits to Group 2
  • the code retrieves groups 1 and 2

1 Comment

I would have ticked all three responses if I could. I chose this one though because it is the one I eventually went with.
3

Get the matched group from index 1 and 2

(\d+) packs? of (\d+)

DEMO

String literals for use in programs: C# (ignore case is also added)

@"(?i)(\d+) packs? of (\d+)"

Read more about Ignore case and Regex.Match

10 Comments

Thanks. Do I just use Regex.Match?
you regex matches \d pack of \d.. why is there a ?
Why the downvote? The answer is fine. ? means 0 or 1.
@sunbabaphu It's to match both packs and pack as well
@sunbabaphu see the sample that OP is posted in question.
|

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.