-
Notifications
You must be signed in to change notification settings - Fork 6
/
_string.lua
59 lines (45 loc) · 1.49 KB
/
_string.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
local String = {}
local function trim (text, left, right, pattern)
assert (type (text) == 'string')
if pattern == nil then
pattern = '%s+'
end
assert (type (pattern) == 'string')
if text == '' then
return ''
end
pattern = '^' .. pattern
if left then
local _, index = text:find (pattern)
if index and index > 0 then
text = text:sub (index + 1)
end
end
if right and text ~= '' then
local _, index = text:reverse ():find (pattern)
if index and index > 0 then
text = text:sub (1, #text - index)
end
end
return text
end
-- Removes leading characters from `text` (`string`) that match an optional
-- non-anchored `pattern` (`string`) and returns the resultant `string`. If
-- `pattern` is not provided, then white space (i.e. `%s+`) is removed.
function String.trim_left (text, pattern)
return trim (text, true, false, pattern)
end
-- Removes trailing characters from `text` (`string`) that match an optional
-- non-anchored `pattern` (`string`) and returns the resultant `string`. If
-- `pattern` is not provided, then white space (i.e. `%s+`) is removed.
function String.trim_right (text, pattern)
return trim (text, false, true, pattern)
end
-- Removes leading and trailing characters from `text` (`string`) that match
-- an optional non-anchored `pattern` (`string`) and returns the resultant
-- `string`. If `pattern` is not provided, then white space (i.e. `%s+`) is
-- removed.
function String.trim (text, pattern)
return trim (text, true, true, pattern)
end
return String