Replacement Issues with dash check (range out of order)

34 Views Asked by At

I have two strings I'm trying to match but keep getting out of bounds errors or unmatch issues.

This is coded in LUA btw.

RegExp1 = "%[%d+%. Trade.-%]"

With string example: "[5. Trade - City] [SomeCharacterName]: Testing Chat"

Should be returned as: "[5. TR] [SomeCharacterName]: Testing Chat"

RegExp2 = "%[%d+%. Trade (Services).-%]"

With string example: "[5. Trade (Services) - City] [SomeCharacterName]: Testing Chat"

Should be returned as: "[5. TRS] [SomeCharacterName]: Testing Chat"

but both RegExp1 and RegExp2 give out of bounds errors and RegExp2 never matches (Services) portion of the string no matter how many variations and escapes I tend to do.

In general I would like to ignore everything after the "-" dash in the regexp and always replace the text at the front of it with something else.

Examples:

[2. Channel - SomeCity]  to [2. CHN]
[2. Channel (Services) - SomeCity]  to [2. CHS]
[2. Channel] to [2. CH]   <--this one is missing the city name
[4. SomeDefense] to [4. SD]

etc.. etc..

Thanks for the help!!!

https://regex101.com/r/sn6axG/1

1

There are 1 best solutions below

0
Wiktor Stribiżew On

First of all, Lua patterns are not regular expressions and can't be tested at regex101.com. .- in Lua patterns is the (?s).*? regex pattern equivalent, and when you used [.-%], you defined an invalid ASCII char range.

In your first case, you can use "(%[%d+%. )Trade.-%]" as the pattern and "%1TR] as the replacement pattern.

In the second case, you can use "(%[%d+%. )Trade %([^()]*%).-%]" pattern and "%1TRS]" replacement.

See the online Lua demo:

local s = "[5. Trade - City] [SomeCharacterName]: Testing Chat"
local result, _ = s:gsub("(%[%d+%. )Trade.-%]", "%1TR]")
print( result )
-- [5. TR] [SomeCharacterName]: Testing Chat

local text = "[5. Trade (Services) - City] [SomeCharacterName]: Testing Chat"
local res, _ = text:gsub("(%[%d+%. )Trade %([^()]*%).-%]", "%1TRS]")
print( res )
-- [5. TRS] [SomeCharacterName]: Testing Chat