Release 0.41.92
[vala-gnome.git] / tests / objects / regex.vala
blob1c517f3851bf0c3073377bc4eb6baed96fb56083
1 using GLib;
4 static Regex get_from_array (int index)
6 Regex[] arr = {
7 /(\d+\.\d+\.\d+)/,
8 /(\d+)\.\d+\.\d+/,
9 /\d+\.(\d+)\.\d+/,
10 /(\d+)\.\d+\.(\d+)/
13 assert (0 <= index <= 3);
14 return arr[index];
17 static Regex get_fixed ()
19 return /(is.*ip)/;
22 class Test : Object {
23 public signal void regexTest (string str);
24 public void run (string s)
26 regexTest (s);
30 void main ()
32 MatchInfo info;
34 // Simple greedy regular expression matching, regex received as a function return value.
35 var str1 = "mississippi";
36 if (get_fixed ().match (str1, 0, out info)) {
37 stdout.printf ("Part of %s is '%s'...\n", str1, info.fetch (1));
38 } else {
39 stdout.printf ("Did not match at all.\n");
42 // Match caseless.
43 var str2 = "demonStration";
44 if (/mon(str.*o)n/i.match (str2, 0, out info)) {
45 stdout.printf ("Part of %s is '%s'...\n", str2, info.fetch (1));
46 } else {
47 stdout.printf ("%s did not match at all.\n", str2);
50 // Match and pick substrings.
51 var ts = "Time: 10:42:12";
52 if (/Time: (..):(..):(..)/.match (ts, 0, out info)) {
53 stdout.printf ("%s\n\thours = %s\n\tminutes = %s\n\tseconds = %s\n\n", ts, info.fetch (1), info.fetch (2), info.fetch (3));
56 // Replace demo: word swapping
57 try {
58 var str = "apple grape";
59 stdout.printf ("'%s' becomes '%s'\n", str, /^([^ ]*) *([^ ]*)/.replace (str, -1, 0, """\2 \1"""));
60 } catch (RegexError err) {
61 // Replacing still needs exception catching
62 message (err.message);
65 // Regex literals in an array
66 for (int i=0; i<4; i++) {
67 if (get_from_array (i).match ("23.3.2010", 0, out info)) {
68 stdout.printf ("Round %d: %s\n", i, info.fetch (1));
72 // ??-operator
73 Regex? r = null;
74 Regex? r1 = null;
75 Regex? r2 = null;
77 r = r1 ?? r2 ?? /match (this)/i;
78 if (r.match ("match THIS", 0, out info)) {
79 stdout.printf ("Match: %s\n", info.fetch (1));
82 // Escape sequences
83 if (/\.\+\(\)\-\?\/\"\$\[\]\*\^/.match (".+()-?/\"$[]*^")) {
84 stdout.printf ("Matches\n");
85 } else {
86 stdout.printf ("Does not match.\n");
89 // Lambda and closure test
90 Regex? rc = /foo(bar)/i;
91 var test = new Test ();
92 test.regexTest.connect ((s) => {
93 if (rc.match (s, 0, out info)) {
94 stdout.printf ("Lambda (closure var.): %s -> %s\n", s, info.fetch (1));
95 } else {
96 stdout.printf ("Does not match.\n");
98 if (/foo(bar)/i.match (s, 0, out info)) {
99 stdout.printf ("Lambda (lit.): %s -> %s\n", s, info.fetch (1));
100 } else {
101 stdout.printf ("Does not match.\n");
104 test.run ("fooBar");
105 test.run ("foobAr");