]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.scl.runtime/scl/String.scl
Migrated source code from Simantics SVN
[simantics/platform.git] / bundles / org.simantics.scl.runtime / scl / String.scl
1 import "Prelude" hiding (group)
2
3 importJava "java.util.regex.Pattern" where
4     data Pattern
5     
6     compile :: String -> Pattern
7     matcher :: Pattern -> String -> Matcher
8
9 importJava "java.util.regex.Matcher" where
10     data Matcher
11
12     matches :: Matcher -> <Proc> Boolean
13     
14     group :: Matcher -> <Proc> String
15
16     @JavaName find
17     matcherFind :: Matcher -> <Proc> Boolean
18     
19     appendReplacement :: Matcher -> StringBuffer -> String -> <Proc> Matcher
20     appendTail :: Matcher -> StringBuffer -> <Proc> StringBuffer
21     
22     @JavaName replaceAll
23     replaceAll_ :: Matcher -> String -> String
24     
25     @JavaName replaceFirst
26     replaceFirst_ :: Matcher -> String -> String
27     
28     quoteReplacement :: String -> String
29
30 importJava "java.lang.StringBuffer" where
31     data StringBuffer
32     
33     @JavaName "<init>"
34     newStringBuffer :: () -> StringBuffer
35     
36     @JavaName toString
37     freezeStringBuffer :: StringBuffer -> <Proc> String
38
39 """
40 @replaceAll pattern replacement text@ replaces all matches of @pattern@ in the @text@
41 by @replacement@.
42 """    
43 replaceAll :: String -> String -> String -> String
44 replaceAll pattern replacement text = 
45     replaceAll_ (matcher (compile pattern) text) replacement 
46     
47 """
48 @replaceFirst pattern replacement text@ replaces the first match of @pattern@ in the @text@
49 by @replacement@.
50 """    
51 replaceFirst :: String -> String -> String -> String
52 replaceFirst pattern replacement text = 
53     replaceFirst_ (matcher (compile pattern) text) replacement 
54
55 """
56 @substituteAll pattern f text@ replaces all matches of @pattern@ in the @text@
57 by the string returned by @f@ given the matched region of the string as a parameter.
58 """
59 substituteAll :: String -> (String -> String) -> String -> String
60 substituteAll pattern f text = runProc do
61     m = matcher (compile pattern) text
62     buf = newStringBuffer ()
63     while (matcherFind m) do
64         appendReplacement m buf $ f $ group m
65     appendTail m buf
66     freezeStringBuffer buf
67
68
69 """
70 @substituteFirst pattern f text@ replaces the first match of @pattern@ in the @text@
71 by the string returned by @f@ given the matched region of the string as a parameter.
72 """
73 substituteFirst :: String -> (String -> String) -> String -> String
74 substituteFirst pattern f text = runProc do
75     m = matcher (compile pattern) text
76     if (matcherFind m) then do
77         buf = newStringBuffer ()    
78         appendReplacement m buf $ f $ group m
79         appendTail m buf
80         freezeStringBuffer buf
81     else text
82