challenge 改行をBRタグに置き換える

一部のHTMLタグを通すフィルタ どう書く?の続編です。 前回の条件を満たしつつ、入力中の改行を<br/>に置き換えてください。ただし、たとえば"<a\nhref=...>"といったようにタグの中に改行がある場合、単純に置換するわけには行かないことに注意してください。

また、ユーザの入力注の<br>は<br/>に変換してください。

このお題はperezvonさんの提案を元にした三部作の二問目です。ご協力ありがとうございました。

Posted feedbacks - Scheme

前回の問題はまったく別の問題なのでここでは考えに入れていません。別の関数に分けておけば再利用できるでしょう。

コードの方は簡単な状態機械でタグの内と外の場合をそれぞれ扱っています。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
(define (newline->br iport oport)
  (define (next) (read-char iport))
  (define (in-tag c)
    (and (not (eof-object? c))
         (case c
           ((#\>) (display c oport) (in-contents (next)))
           (else (display c oport) (in-tag (next))))))
  (define (in-contents c)
    (and (not (eof-object? c))
         (case c
           ((#\newline) (display "<br/>" oport) (in-contents (next)))
           ((#\<) (display c oport) (in-tag (next)))
           (else (display c oport) (in-contents (next))))))
  (in-contents (next)))

(define (main args)
  (print
   (call-with-input-file (cadr args)
     (lambda (iport)
       (regexp-replace-all #/<br>/
                           (call-with-output-string
                             (lambda (oport)
                               (newline->br iport oport)))
                           "<br/>"))))
  0)

Index

Feed

Other

Link

Pathtraq

loading...