Racket 编程

2 部分 · 高级特性

正则表达式与解析

正则表达式与解析

掌握正则表达式操作,以及使用解析器组合子处理结构化文本。

正则表达式

#lang racket

;; 基本匹配
(regexp-match #rx"hello" "say hello world")
; => '("hello")

;; 捕获组
(regexp-match #rx"(\\w+)@(\\w+)" "user@example.com")
; => '("user@example.com" "user" "example")

;; 替换
(regexp-replace #rx"world" "hello world" "Racket")
; => "hello Racket"

;; 全部替换
(regexp-replace* #rx"\\d+" "a1b2c3" "X")
; => "aXbXcX"

;; 分割
(regexp-split #rx"," "a,b,c,d")
; => '("a" "b" "c" "d")

正则表达式类型

#rx"pattern"   ; 正则表达式(字节)
#px"pattern"   ; Perl 兼容正则表达式(支持 \\d, \\w 等)

解析器组合子

对于比正则更复杂的文本处理,可以使用解析器组合子:

(require parser-tools/lex)

;; 定义词法分析器
(define-tokens value-tokens (NUM ID))
(define-empty-tokens op-tokens (PLUS MINUS EOF))

(define my-lexer
  (lexer
   [(repetition 1 +inf.0 numeric) (token-NUM (string->number lexeme))]
   ["+" (token-PLUS)]
   ["-" (token-MINUS)]
   [whitespace (my-lexer input-port)]
   [(eof) 'EOF]))

小结

正则表达式处理简单的文本匹配和提取,解析器组合子处理复杂的结构化文本。选择合适的工具取决于你的需求复杂度。