Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot use Percent (%) in a Lua pattern

Tags:

lua

I have this line in a Lua script that crash my software every time:

fmt_url_map = string.gsub( fmt_url_map, '%2F','/' )

I want to replace all occurrences of %2F occurrences in a text to /. If I remove the % , it doesn't crash.

What am I doing wrong ?

like image 543
bratao Avatar asked Aug 04 '11 01:08

bratao


People also ask

How do I use percentage in Lua?

% is a special symbol in Lua patterns. It's used to represent certain sets of characters, (called character classes). For example, %a represents any letter. If you want to literally match % you need to use %% .

How do you put a percent in a string?

You can do this by using %% in the printf statement. For example, you can write printf(“10%%”) to have the output appear as 10% on the screen.

What is %w Lua?

Valid in Lua, where %w is (almost) the equivalent of \w in other languages. ^[%w-.]+$ means match a string that is entirely composed of alphanumeric characters (letters and digits), dashes or dots.

Does Lua use regex?

Instead of using regex, the Lua string library has a special set of characters used in syntax matches.


2 Answers

% is a special symbol in Lua patterns. It's used to represent certain sets of characters, (called character classes). For example, %a represents any letter. If you want to literally match % you need to use %%. See this section of the Lua Reference Manual for more information. I suspect you're running into problems because %F is not a character class.

like image 73
Alex Avatar answered Sep 18 '22 05:09

Alex


You need to escape the '%' with another '%'

fmt_url_map = string.gsub( fmt_url_map, '%%2F','/' )
like image 25
Tuomas Pelkonen Avatar answered Sep 19 '22 05:09

Tuomas Pelkonen