📰 Latest: HaasOnline Academy Is Back — Structured Education for Smarter Trade Bots
Account
Strings

String.match (regex)

String.match (regex)

Lua's string.match() function searches for patterns in strings using Lua's pattern matching syntax. While not full regular expressions, Lua patterns are powerful and sufficient for most text processing tasks in trading strategies.

string.match()

Searches for a pattern in a string and returns the matched text.

string.match(value, pattern [, index])

Basic Usage

local text = "Price: 45000"
local match = string.match(text, "%d+")

Log(match)  -- Outputs: 45000

Pattern Matching Syntax

Lua uses special characters to define patterns:

Pattern Matches Example
. Any character ".o" matches "lo", "yo"
%a Any letter "%a+" matches "Hello"
%d Any digit "%d+" matches "45000"
%s Whitespace character "%s+" matches spaces, tabs
%w Alphanumeric character "%w+" matches "BTC123"
^ Start of string "^Hello" matches at start
$ End of string "end$" matches at end
+ One or more "%d+" matches one or more digits
* Zero or more "%d*" matches zero or more digits
- Zero or more (shortest) ".-" matches shortest sequence
? Optional (zero or one) "%.?" matches optional decimal

Extracting Numbers

Extracting Price

local text = "Entry at 45000.50"
local price = string.match(text, "%d+%.?%d*")

Log(price)  -- Outputs: 45000.50

Extracting Multiple Numbers

local text = "RSI: 25.5, MACD: 15.2"

for number in string.gmatch(text, "%d+%.?%d*") do
    Log(number)
end

-- Outputs:
-- 25.5
-- 15.2

Extracting Integer

local text = "Quantity: 100"
local quantity = string.match(text, "%d+")

Log(quantity)  -- Outputs: 100

Extracting Text

Extracting Words

local text = "BTC_USDT trading"
local market = string.match(text, "%u%u%u")

Log(market)  -- Outputs: BTC

Extracting Between Markers

local text = "Price: [45000]"
local price = string.match(text, "%[(.+)%]")

Log(price)  -- Outputs: 45000

Extracting Currency Codes

local text = "Trading BTC/USDT pair"
local pair = string.match(text, "%u+/%u+")

Log(pair)  -- Outputs: BTC/USDT

Character Classes

Matching Letters

local text = "abc123"
local letters = string.match(text, "%a+")

Log(letters)  -- Outputs: abc

Matching Digits

local text = "Price: 45000"
local digits = string.match(text, "%d+")

Log(digits)  -- Outputs: 45000

Matching Alphanumeric

local text = "BTC123 is valid"
local code = string.match(text, "%w+")

Log(code)  -- Outputs: BTC123

Matching Specific Ranges

local text = "RSI value: 75"
local value = string.match(text, "[0-9]+")

Log(value)  -- Outputs: 75

Anchors

Start of String

local text = "Hello World"
local match = string.match(text, "^Hello")

Log(match)  -- Outputs: Hello

End of String

local text = "Price: 45000"
local match = string.match(text, "%d+$")

Log(match)  -- Outputs: 45000

Both Start and End

local text = "BTC_USDT"
local match = string.match(text, "^%u+_%u+$")

Log(match)  -- Outputs: BTC_USDT

Quantifiers

One or More (+)

local text = "Price: 45000"
local price = string.match(text, "%d+")

Log(price)  -- Outputs: 45000

Zero or More (*)

local text = "Price: 45000"
local match = string.match(text, "Price:%s*%d+")

Log(match)  -- Outputs: Price: 45000

Optional (?)

local text = "Price: 45000.50"
local price = string.match(text, "%d+%.?%d*")

Log(price)  -- Outputs: 45000.50

local text2 = "Price: 45000"
local price2 = string.match(text2, "%d+%.?%d*")

Log(price2)  -- Outputs: 45000

Sets and Ranges

Character Sets

local text = "BTC_USDT"
local match = string.match(text, "[A-Z_]+")

Log(match)  -- Outputs: BTC_USDT

Negated Sets

local text = "Price: $45000"
local price = string.match(text, "[^$]+")

Log(price)  -- Outputs: Price:  (matches everything except $)

Number Ranges

local text = "RSI: 75"
local value = string.match(text, "[5-7][0-9]")

Log(value)  -- Outputs: 75 (matches 50-79 range)

Capturing Groups

Basic Capturing

local text = "BTC_USDT"
local base, quote = string.match(text, "(%w+)_(%w+)")

Log("Base: " .. base)    -- Outputs: Base: BTC
Log("Quote: " .. quote)  -- Outputs: Quote: USDT

Multiple Captures

local text = "Entry: 45000 at 10:30"
local price, time = string.match(text, "Entry: (%d+) at (%d+:%d+)")

Log("Price: " .. price)  -- Outputs: Price: 45000
Log("Time: " .. time)    -- Outputs: Time: 10:30

Nested Captures

local text = "RSI(14) = 25.5"
local indicator, period, value = string.match(text, "(%w+)%((%d+)%) = (%d+%.%d+)")

Log(indicator)  -- Outputs: RSI
Log(period)     -- Outputs: 14
Log(value)      -- Outputs: 25.5

string.gmatch()

Iterates over all matches in a string.

Find All Numbers

local text = "RSI: 25, MACD: 15, ATR: 150"

for number in string.gmatch(text, "%d+") do
    Log(number)
end

-- Outputs:
-- 25
-- 15
-- 150

Find All Words

local text = "BTC ETH LTC XRP"

for coin in string.gmatch(text, "%u+") do
    Log(coin)
end

-- Outputs:
-- BTC
-- ETH
-- LTC
-- XRP

Find All Patterns

local text = "BTC_USDT ETH_USDT LTC_USDT"

for pair in string.gmatch(text, "%w+_%w+") do
    Log(pair)
end

-- Outputs:
-- BTC_USDT
-- ETH_USDT
-- LTC_USDT

string.find()

Finds the position of a pattern match.

local text = "Hello World"
local start, endPos = string.find(text, "World")

Log("Start: " .. start)    -- Outputs: Start: 7
Log("End: " .. endPos)      -- Outputs: End: 11

Trading Use Cases

Parse Trade Messages

local message = "Entry LONG BTC_USDT at 45000"
local direction, market, price = string.match(message,
    "Entry (%a+) (%w+) at (%d+)")

Log("Direction: " .. direction)  -- Outputs: Direction: LONG
Log("Market: " .. market)        -- Outputs: Market: BTC_USDT
Log("Price: " .. price)          -- Outputs: Price: 45000

Extract Indicator Values

local text = "RSI(14): 25.5, MACD(12,26,9): 15.2"

-- Extract RSI info
local rsiIndicator, rsiPeriod, rsiValue = string.match(text,
    "(RSI)%((%d+)%)%s*:%s*([%d%.]+)")

Log(rsiIndicator)  -- Outputs: RSI
Log(rsiPeriod)     -- Outputs: 14
Log(rsiValue)      -- Outputs: 25.5

Validate Market Format

local market = "BTC_USDT"

if string.match(market, "^%u+_%u+$") then
    Log("Valid market format")
else
    Log("Invalid market format")
end

Extract Timestamp

local timestamp = "2024-01-15 10:30:45"
local year, month, day = string.match(timestamp, "(%d+)-(%d+)-(%d+)")

Log("Year: " .. year)    -- Outputs: Year: 2024
Log("Month: " .. month)  -- Outputs: Month: 01
Log("Day: " .. day)      -- Outputs: Day: 15

Parse Log Data

local log = "[2024-01-15] Entry: LONG at 45000, RSI: 25.5"

local date, action, price, rsi = string.match(log,
    "%[(.-)%]%s*(.-):%s*%a+%s*at%s*(%d+),%s*RSI:%s*([%d%.]+)")

Log(date)    -- Outputs: 2024-01-15
Log(action)  -- Outputs: Entry
Log(price)   -- Outputs: 45000
Log(rsi)     -- Outputs: 25.5

Clean Text

local text = "Price: $45,000.50 USD"

-- Remove currency symbols and commas
local clean = string.gsub(text, "[$,]", "")
local price = string.match(clean, "%d+%.?%d*")

Log(price)  -- Outputs: 45000.50

Extract URLs or Links

local text = "Visit https://www.example.com for more info"
local url = string.match(text, "https?://%S+")

Log(url)  -- Outputs: https://www.example.com

Common Patterns

Email Pattern

local email = "[email protected]"
local domain = string.match(email, "@(%S+)")

Log(domain)  -- Outputs: exchange.com

Currency Pair Pattern

local pair = "BTC/USDT"
local base, quote = string.match(pair, "(%w+)/(%w+)")

Log(base)   -- Outputs: BTC
Log(quote)  -- Outputs: USDT

Decimal Number Pattern

local text = "Price: 45000.50"
local price = string.match(text, "%d+%.?%d*")

Log(price)  -- Outputs: 45000.50

Integer Range Pattern

local text = "RSI: 75"
local rsi = string.match(text, "%d+")

if tonumber(rsi) >= 0 and tonumber(rsi) <= 100 then
    Log("Valid RSI range")
end

Escaping Special Characters

Escape special characters with %:

local text = "Price: 50% discount"
local match = string.match(text, "%d+%%")

Log(match)  -- Outputs: 50%

Best Practices

  1. Start simple - Use basic patterns before complex ones
  2. Test patterns - Verify patterns work with sample data
  3. Use capturing groups - Extract multiple parts in one match
  4. Combine with other functions - Use with string.gsub(), string.find()
  5. Handle failures - Check if match returns nil
  6. Use string.gmatch() - For finding all matches
  7. Escape special chars - Use % before ., %, +, *, ?, ^, $, (, ), [, ]

Summary

  • string.match() - Search for patterns in strings
  • Patterns - Lua's simplified regex syntax
  • Character classes - %a, %d, %s, %w
  • Quantifiers - +, *, ?, -
  • Anchors - ^, $
  • Capturing groups - Extract multiple parts with ()
  • string.gmatch() - Iterate over all matches
  • string.find() - Find position of matches
  • Trading uses - Parse messages, extract values, validate formats

Lua's pattern matching is powerful for text processing in trading strategies. Master these patterns to parse logs, extract data, and validate text formats efficiently.