Levy
Levy

Reputation: 231

How to match this pattern in lua regex so it can catch what's inside the string

I'm trying to put two asterisks in between words that a enclosed by underscores.

So far, I succeeded matching the pattern when it's just one word inside the underscores, if there's a space in the middle, the pattern fails.

How do I write the correct pattern to find the words in between the underscores and put asterisks in between them? Here's a MWE of my code:

function string:add(start, fim, word)
    return self:sub(1,start-1) .. "**" .. word .. "**" .. self:sub(fim+1)
end

regex = "In this string I'm putting _many_ words to test if I _wrote_ the code right to _match patterns_."

while regex:find("_(%w+)_") ~= nil do
    start, fim = regex:find("_(%w+)_")
    regex = regex:add(start, fim, regex:match("_(%w+)_"))
end

print(regex)

The output is:

In this string I'm putting **many** words to test if I **wrote** the code right to _match patterns_.

As it can be seen, in _match patterns_ there are two words and a space, so my pattern _(%w+)_ skips it. How do I include it too?

Upvotes: 2

Views: 568

Answers (2)

Mike V.
Mike V.

Reputation: 2205

you can simply find the characters between underscores excluding space at the beginning:

local str = "In this string I'm putting _many_ words to test if I _wrote_ the code right to _match patterns_."

print(str:gsub("_([^%s].-)_","**%1**"))

-- find the words --
for words in str:gmatch("_([^%s].-)_") do
  print(words)
end

Upvotes: 2

Nifim
Nifim

Reputation: 5031

You can make a set using [] and define that set to allow for alphanumeric characters and spaces:

regex:find("_([%w%s]+)_")

Here is a resource where you can learn more about lua patterns:

FHUG: Understanding Lua Patterns

Upvotes: 1

Related Questions