|
1 | 1 | (ns wisp.string
|
2 |
| - (:require [wisp.runtime :refer [str subs re-matches nil? string?]] |
| 2 | + (:require [wisp.runtime :refer [str subs re-matches nil? string? re-pattern?]] |
3 | 3 | [wisp.sequence :refer [vec empty?]]))
|
4 | 4 |
|
5 | 5 | (defn split
|
|
8 | 8 | [string pattern limit]
|
9 | 9 | (.split string pattern limit))
|
10 | 10 |
|
| 11 | +(defn split-lines |
| 12 | + "Splits s on \n or \r\n." |
| 13 | + [s] |
| 14 | + (split s #"\n|\r\n")) |
| 15 | + |
11 | 16 | (defn join
|
12 | 17 | "Returns a string of all elements in coll, as returned by (seq coll),
|
13 | 18 | separated by an optional separator."
|
|
40 | 45 | (str (upper-case (subs s 0 1))
|
41 | 46 | (lower-case (subs s 1)))))
|
42 | 47 |
|
| 48 | +(def ^:private ESCAPE_PATTERN |
| 49 | + (RegExp. "([-()\\[\\]{}+?*.$\\^|,:#<!\\\\])" "g")) |
| 50 | + |
| 51 | +(defn pattern-escape |
| 52 | + [source] |
| 53 | + (.replace (.replace source ESCAPE_PATTERN "\\$1") |
| 54 | + (RegExp. "\\x08" "g"), "\\x08")) |
| 55 | + |
| 56 | +(defn replace-first |
| 57 | + "Replaces the first instance of match with replacement in s. |
| 58 | + match/replacement can be: |
| 59 | +
|
| 60 | + string / string |
| 61 | + pattern / (string or function of match)." |
| 62 | + [string match replacement] |
| 63 | + (.replace string match replacement)) |
| 64 | + |
43 | 65 | (defn replace
|
44 | 66 | "Replaces all instance of match with replacement in s.
|
45 | 67 |
|
|
51 | 73 |
|
52 | 74 | See also replace-first."
|
53 | 75 | [string match replacement]
|
54 |
| - (.replace string match replacement)) |
| 76 | + (cond (string? match) |
| 77 | + (replace string (RegExp. pattern-escape match) "g" replacement) |
| 78 | + |
| 79 | + (re-pattern? match) |
| 80 | + (.replace s (RegExp. (.-source match) "g") replacement) |
| 81 | + |
| 82 | + :else |
| 83 | + (throw (str "Invalid match arg: " match)))) |
55 | 84 |
|
56 | 85 |
|
57 | 86 | ;(def **WHITESPACE** (str "[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000"
|
|
97 | 126 | (or (nil? string)
|
98 | 127 | (empty? string)
|
99 | 128 | (re-matches **SPACES** string)))
|
| 129 | + |
| 130 | +(defn reverse |
| 131 | + "Returns s with its characters reversed." |
| 132 | + [string] |
| 133 | + (join "" (.reverse (split string "")))) |
0 commit comments