diff options
Diffstat (limited to 'lib/pure')
-rwxr-xr-x | lib/pure/pegs.nim | 20 | ||||
-rwxr-xr-x | lib/pure/re.nim | 12 |
2 files changed, 32 insertions, 0 deletions
diff --git a/lib/pure/pegs.nim b/lib/pure/pegs.nim index 201f13111..e5a655b2e 100755 --- a/lib/pure/pegs.nim +++ b/lib/pure/pegs.nim @@ -1371,7 +1371,27 @@ proc peg*(pattern: string): TPeg = ## peg"{\ident} \s* '=' \s* {.*}" result = parsePeg(pattern, "pattern") +proc escapePeg*(s: string): string = + ## escapes `s` so that it is matched verbatim when used as a peg. + result = "" + var inQuote = false + for c in items(s): + case c + of '\0'..'\31', '\'', '"', '\\': + if inQuote: + result.add('\'') + inQuote = false + result.add("\\x") + result.add(toHex(ord(c), 2)) + else: + if not inQuote: + result.add('\'') + inQuote = true + result.add(c) + if inQuote: result.add('\'') + when isMainModule: + assert escapePeg("abc''def'") == r"'abc'\x27\x27'def'\x27" assert match("(a b c)", peg"'(' @ ')'") assert match("W_HI_Le", peg"\y 'while'") assert(not match("W_HI_L", peg"\y 'while'")) diff --git a/lib/pure/re.nim b/lib/pure/re.nim index b4aa75637..dfa191963 100755 --- a/lib/pure/re.nim +++ b/lib/pure/re.nim @@ -273,6 +273,18 @@ proc split*(s: string, sep: TRegEx): seq[string] = ## Splits the string `s` into substrings. accumulateResult(split(s, sep)) +proc escapeRe*(s: string): string = + ## escapes `s` so that it is matched verbatim when used as a regular + ## expression. + result = "" + for c in items(s): + case c + of 'a'..'z', 'A'..'Z', '0'..'9', '_': + result.add(c) + else: + result.add("\\x") + result.add(toHex(ord(c), 2)) + const ## common regular expressions reIdentifier* = r"\b[a-zA-Z_]+[a-zA-Z_0-9]*\b" ## describes an identifier reNatural* = r"\b\d+\b" ## describes a natural number |