diff options
author | Louis Pilfold <louis@lpil.uk> | 2021-08-26 22:33:03 +0100 |
---|---|---|
committer | Louis Pilfold <louis@lpil.uk> | 2021-08-27 00:37:15 +0100 |
commit | cb80cf508ac0990038ec6ee6cd90cb61eaeabe5c (patch) | |
tree | 1de16fb5230d355ab2e1518ca90be3efba6e7b65 | |
parent | 794f0740fa98a218bb210da1d96f39409e5907c6 (diff) | |
download | gleam_stdlib-cb80cf508ac0990038ec6ee6cd90cb61eaeabe5c.tar.gz gleam_stdlib-cb80cf508ac0990038ec6ee6cd90cb61eaeabe5c.zip |
Regex compile and check
-rw-r--r-- | src/gleam_stdlib.js | 18 | ||||
-rw-r--r-- | test/gleam/regex_test.gleam | 43 |
2 files changed, 35 insertions, 26 deletions
diff --git a/src/gleam_stdlib.js b/src/gleam_stdlib.js index c7db142..d2454ba 100644 --- a/src/gleam_stdlib.js +++ b/src/gleam_stdlib.js @@ -7,6 +7,7 @@ import { toBitString, stringBits, } from "./gleam.js"; +import { CompileError as RegexCompileError } from "./gleam/regex.js"; const Nil = undefined; @@ -228,3 +229,20 @@ export function bit_string_slice(bits, position, length) { export function codepoint(int) { return new UtfCodepoint(int); } + +export function regex_check(regex, string) { + return regex.test(string); +} + +export function compile_regex(pattern, options) { + try { + let flags = ""; + if (options.case_insensitive) flags += "i"; + if (options.multi_line) flags += "m"; + return new Ok(new RegExp(pattern, flags)); + } catch (error) { + return new Error( + new RegexCompileError(error.message, error.columnNumber || 0) + ); + } +} diff --git a/test/gleam/regex_test.gleam b/test/gleam/regex_test.gleam index 91d43c6..367b810 100644 --- a/test/gleam/regex_test.gleam +++ b/test/gleam/regex_test.gleam @@ -1,27 +1,18 @@ import gleam/regex.{CompileError, Match, Options} import gleam/should +import gleam/io +import gleam/option.{None, Some} -if erlang { - import gleam/io - import gleam/option.{None, Some} - - pub fn from_string_test() { - assert Ok(re) = regex.from_string("[0-9]") - - regex.check(re, "abc123") - |> should.equal(True) +pub fn from_string_test() { + assert Ok(re) = regex.from_string("[0-9]") - regex.check(re, "abcxyz") - |> should.equal(False) + regex.check(re, "abc123") + |> should.equal(True) - assert Error(from_string_err) = regex.from_string("[0-9") + regex.check(re, "abcxyz") + |> should.equal(False) - from_string_err - |> should.equal(CompileError( - error: "missing terminating ] for character class", - byte_index: 4, - )) - } + assert Error(_) = regex.from_string("[0-9") } pub fn compile_test() { @@ -38,17 +29,17 @@ pub fn compile_test() { |> should.equal(True) } -if erlang { - pub fn check_test() { - assert Ok(re) = regex.from_string("^f.o.?") +pub fn check_test() { + assert Ok(re) = regex.from_string("^f.o.?") - regex.check(re, "foo") - |> should.equal(True) + regex.check(re, "foo") + |> should.equal(True) - regex.check(re, "boo") - |> should.equal(False) - } + regex.check(re, "boo") + |> should.equal(False) +} +if erlang { pub fn split_test() { assert Ok(re) = regex.from_string(" *, *") |