summaryrefslogtreecommitdiff
path: root/appl/lib/regexutils.b
blob: 4040f0bf197d35dcbebb9bdc94819792b8978eaa (plain)
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
60
61
62
63
64
65
implement RegexUtils;

# matching and substitution functions
# evb@lucent.com

include "sys.m";
	sys: Sys;
	
include "regexutils.m";

init()
{
	if (sys == nil)
		sys = load Sys Sys->PATH;
		
	regex = load Regex Regex->PATH;
	if (regex == nil)
		raise "fail: Regex not loaded";
}

match(pattern: Regex->Re, s: string): string
{
	pos := regex->execute(pattern, s);
	if (pos == nil)
		return "";
	(beg, end) := pos[0];
	
	return s[beg:end];
}

match_mult(pattern: Regex->Re, s: string): array of (int, int)
{
	return regex->execute(pattern, s);
}

sub(text, pattern, new: string): string
{
	return sub_re(text, regex->compile(pattern, 0).t0, new);
}

sub_re(text: string, pattern: Regex->Re, new: string): string
{
	pos := regex->execute(pattern, text);
	if (pos == nil) 
		return text;
	
	(beg, end) := pos[0];
	newline := text[:beg] + new + text[end:];
	return newline;
}

subg(text, pattern, new: string): string
{
	return subg_re(text, regex->compile(pattern, 0).t0, new);
}

subg_re(text: string, pattern: Regex->Re, new: string): string
{
	oldtext := text;
	while ( (text = sub_re(text, pattern, new)) != oldtext) {
		oldtext = text;
	}

	return text;
}