Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lua Regular expression for matching key phrase with value adopted from PHP

I have a regular expression pattern that works for PCRE(PHP) that I would like to use in a lua file.

My objective is to inspect a value (string) to see if it contains a key identifier then to grab the value.

The test string may contain various characters including alphanumeric and special characters. Inside the string is a key followed by a value:

str = 'sample12_3 Word [link:a12]'

The key phrase to find is "[link:]" and the value it must return is whatever is following the ':' semicolon and before the closing square ']' bracket

[link:$value]

The PCRE(PHP) expression is:

\[(link):(.+):?[^\[\]]*\]

Group 1: 'link' Group 2: 'a12'

Can anyone help me with the correct lua iteration for this expression?

like image 628
GrumpyDog Avatar asked Feb 01 '26 11:02

GrumpyDog


1 Answers

Lua patterns are not considered regular expressions as they are not capable of matching regular language. However, you are lucky here, you can translate the expression into

local str = 'sample12_3 Word [link:a12]'
result, _ = str:match("%[link:([^][]*)]")
print(result) -- => a12

See the Lua demo.

Details

  • %[ - matches a literal [ char
  • link: - literal link: text
  • ([^][]*) - capturing group #1: any zero or more chars other than [ and ]
  • ] - a ] char.

The :match() function will return the contents of the capturing group here, since the capturing group is present in the pattern.

like image 141
Wiktor Stribiżew Avatar answered Feb 03 '26 23:02

Wiktor Stribiżew