Get character before and after match in string

I've the a few strings and somewhere inside the string there is a /. Like bis 0/5 nta.

I'm trying to get the number on each side of the / and including / like 0/5.

I have tried with splitting the string by / and taking the first / last character of the splitted string, but im trying to make it more simple.

for i in string.gmatch(example, "/") do
   print(i)
end

I've also tried:

s = "bis 0/5 nta"
a,b = s:match("(.+)/(.+)")

Is there some way to get the 0/5 from bis 0/5 nta?

Upvotes: 1

Views: 123

Answers (1)

Allister
Allister

Reputation: 911

You don't need the parenthesis. Without them, the entire pattern will become the match. You just need to be more specific with your pattern.

str = "bis 0/5 nta"
x = str:match('%d+/%d+') --%d+ means match one or more digits
print(x) --0/5

If you're only ever going to be looking for matches like 1/2 or 100/253 this will work. If you have more specific needs put them in a comment and I'll help you work on the pattern.

Upvotes: 2

Related Questions