2

I wrote (?<=;)[^\^]* regex but I have problem with transforming it to use it in Lua. I want to transform

^#57df44;Cobblestone^white;

into

Cobblestone

but if the string does not contain any color code then it should be returned "as is".

Could someone help me with this?

1
  • 1
    s = s:gsub("^.-;(.-)^.*$", "%1") Commented Aug 29, 2017 at 14:43

1 Answer 1

2

Use a capturing group:

local s = "^#57df44;Cobblestone^white;"
res = s:match(";([^^]*)") or s
print( res )
-- Cobblestone

See the Lua demo.

Here,

  • ; - matches the first ;
  • ([^^]*) - Capturing group 1 matches any 0+ chars other than ^ into Group 1

The string.match will only return the captured part if the capturing group is defined in the pattern.

More details

As is mentioned in comments, you might use a frontier pattern %f[^:] instead of (?<=:) in the current scenario.

The frontier pattern %f followed by a set detects the transition from "not in set" to "in set".

However, the frontier pattern is not a good substitute for a positive lookbehind (?<=:) because the latter can deal with sequences of patterns, while a frontier pattern only works with single atoms. So, %f[^:] means place in string between : and a non-:. Howerver, once you need to match any 0+ chars other than ^ after city=, a frontier pattern would be a wrong construct to use. So, it is not that easily scalable as a string.match with a capturing group.

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

7 Comments

Here is a demo for multiple occurrences. But I suspect only the first match is what is necessary, so string.match is what you need.
It mostly works, but it fails if text has no color codes (returns nil). This minor issue can be however fixed with simple or. s:match(";([^^]*)") or s;
@user2463506 Sorry, I overlooked that part of the question. Yes, looks like that will do. I added the or bit to the answer.
string.match(s, '%f[^;]([^^]*)')
@moteus - You can omit parentheses: s:match"%f[^;][^^]*"
|

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.