Jump to content

gsub


Skream

Recommended Posts

i gotta the following code 

$cpf = "09551130401";
$returnValue = preg_replace('/^(\\d{3})(\\d{3})(\\d{3})(\\d{2})/', '$1.$2.$3-$4', $cpf, -1);

and this works fine

I've tried to do the same in lua but it doenst work

	local cpf = tostring(09551130401) 
	
	print(string.gsub(cpf, '/^(\\d{3})(\\d{3})(\\d{3})(\\d{2})/',  '$1.$2.$3-$4'))
	print(cpf)

 

Edited by Skream
Link to comment

Lua patterns are not the same thing as regular expressions. Firstly, Lua patterns don't have quantifiers {n} I believe, so you have to expand the pattern:

^(\\d{3})(\\d{3})(\\d{3})(\\d{2})

 into 

^(\\d\\d\\d)(\\d\\d\\d)(\\d\\d\\d)(\\d\\d)

Secondly, Lua patterns use different notation (%d rather than \d):

^(%d%d%d)(%d%d%d)(%d%d%d)(%d%d)

and to use the captures you also use % rather than $

local cpf = string.format("%011d", 09551130401) -- format the number into an 11 digit number (makes sure the leading zeros are there)
print(string.gsub(cpf, '^(%d%d%d)(%d%d%d)(%d%d%d)(%d%d)', '%1.%2.%3.%4')) -- "095.511.304.01"
print(cpf) -- "09551130401"

Read more about Lua patterns on the Lua manual and lua-users.org

Edited by MrTasty
Link to comment
3 hours ago, MrTasty said:

Lua patterns are not the same thing as regular expressions. Firstly, Lua patterns don't have quantifiers {n} I believe, so you have to expand the pattern:


^(\\d{3})(\\d{3})(\\d{3})(\\d{2})

 into 


^(\\d\\d\\d)(\\d\\d\\d)(\\d\\d\\d)(\\d\\d)

Secondly, Lua patterns use different notation (%d rather than \d):


^(%d%d%d)(%d%d%d)(%d%d%d)(%d%d)

and to use the captures you also use % rather than $


local cpf = string.format("%011d", 09551130401) -- format the number into an 11 digit number (makes sure the leading zeros are there)
print(string.gsub(cpf, '^(%d%d%d)(%d%d%d)(%d%d%d)(%d%d)', '%1.%2.%3.%4')) -- "095.511.304.01"
print(cpf) -- "09551130401"

Read more about Lua patterns on the Lua manual and lua-users.org

I tried your example here and I got a negative number output

Edited by Skream
Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...