1+ import Foundation
2+
3+ func RunTest( _ testInput: TestInput ) -> TestOutput {
4+
5+ if testInput. regex == nil || testInput. regex == " " {
6+ return TestOutput ( success: false , html: nil , message: " No regular expression to test! " )
7+ }
8+
9+ let regexStr = testInput. regex ?? " "
10+ let replacement = testInput. replacement ?? " "
11+
12+ var html = String ( )
13+ html += " <table class= \" table table-bordered table-striped \" style= \" width:auto; \" > "
14+ html += " <tbody> "
15+ html += " <tr> "
16+ html += " <td>Regular Expression</td> "
17+ html += " <td> \( escapeHtml ( regexStr) ) </td> "
18+ html += " </tr> "
19+ if replacement != " " {
20+ html += " <tr> "
21+ html += " <td>Replacement</td> "
22+ html += " <td> \( escapeHtml ( replacement) ) </td> "
23+ html += " </tr> "
24+ }
25+ html += " </tbody> "
26+ html += " </table> "
27+
28+ do {
29+ _ = try Regex ( regexStr)
30+ } catch {
31+ return TestOutput ( success: false , html: html, message: " Invalid regular expression! Error: \( error. localizedDescription) " )
32+ }
33+
34+ let regex = try ! Regex ( regexStr)
35+
36+ if testInput. input == nil || testInput. input!. count == 0 {
37+ return TestOutput ( success: false , html: html, message: nil )
38+ }
39+
40+ html += " <table class= \" table table-bordered table-striped \" style= \" width:auto; \" > "
41+ html += " <thead> "
42+ html += " <tr> "
43+ html += " <th>Test</th> "
44+ html += " <th>Target String</th> "
45+ html += " <th>contains</th> "
46+ html += " <th>replacingOccurrences</th> "
47+ html += " <th>wholeMatch</th> "
48+ html += " </tr> "
49+ html += " </thead> "
50+ html += " <tbody> "
51+ var testIndex = 0 ;
52+ for input in testInput. input! {
53+ testIndex += 1
54+ if input == " " {
55+ continue
56+ }
57+ let contains = input. contains ( regexStr)
58+ let replace = input. replacingOccurrences ( of: regexStr, with: replacement, options: testInput. option? . contains ( " i " ) == true ? . caseInsensitive : [ ] )
59+ let wholeMatch = input. wholeMatch ( of: regex) ;
60+ let wholeMatchStr = wholeMatch == nil ? " <i>nil</i> " : escapeHtml ( " \( wholeMatch) " ) ;
61+ html += " <tr> "
62+ html += " <td class= \" text-center \" > \( testIndex) </td> "
63+ html += " <td> \( escapeHtml ( input) ) </td> "
64+ html += " <td> \( contains ? " yes " : " no " ) </td> "
65+ html += " <td> \( escapeHtml ( replace) ) </td> "
66+ html += " <td> \( wholeMatchStr) </td> "
67+ html += " </tr> "
68+ }
69+ html += " </tbody> "
70+ html += " </table> "
71+
72+ return TestOutput ( success: true , html: html, message: nil )
73+ }
74+
75+ import Foundation
76+
77+ func escapeHtml( _ input: String ) -> String {
78+ var escapedString = input
79+ escapedString = escapedString. replacingOccurrences ( of: " & " , with: " & " )
80+ escapedString = escapedString. replacingOccurrences ( of: " < " , with: " < " )
81+ escapedString = escapedString. replacingOccurrences ( of: " > " , with: " > " )
82+ return escapedString
83+ }
0 commit comments