尝试解析以下文本文件:
prefix1 prefix2 name1(
type1 name1,
type2 name2
);
使用以下正则表达式:
\\s*prefix1\\s*prefix2\\s*(\\w[\\w\\d_]*).*\\(\\s*([^\\)]*\\))\\s*;\\s*
结果我得到以下两组(寄存器):"name1(
"
和
"(
type1 name1,
type2 name2
)"
(这里引号限制了字符串,包括\n)
我不明白为什么第一组
(\w[\w\d_]*)
匹配以下 .*
部分。而且,我无法摆脱不必要的尾部!
我的错误是什么?
地址:解析的正则表达式:
(cl-ppcre::parse-string "\\s*prefix1\\s*prefix2\\s*(\\w[\\w\\d_]*).*\\(\\s*([^\\)]*\\))\\s*;\\s*")
(:SEQUENCE (:GREEDY-REPETITION 0 NIL :WHITESPACE-CHAR-CLASS) "prefix1"
(:GREEDY-REPETITION 0 NIL :WHITESPACE-CHAR-CLASS) "prefix2"
(:GREEDY-REPETITION 0 NIL :WHITESPACE-CHAR-CLASS)
(:REGISTER
(:SEQUENCE :WORD-CHAR-CLASS
(:GREEDY-REPETITION 0 NIL (:CHAR-CLASS :WORD-CHAR-CLASS :DIGIT-CLASS #\_))))
(:GREEDY-REPETITION 0 NIL :EVERYTHING) #\(
(:GREEDY-REPETITION 0 NIL :WHITESPACE-CHAR-CLASS)
(:REGISTER
(:SEQUENCE (:GREEDY-REPETITION 0 NIL (:INVERTED-CHAR-CLASS #\))) #\)))
(:GREEDY-REPETITION 0 NIL :WHITESPACE-CHAR-CLASS) #\;
(:GREEDY-REPETITION 0 NIL :WHITESPACE-CHAR-CLASS))
添加 2:
完整的来源:
;; Requirements:
;; cl-ppcre
(defparameter *name-and-parameters-list* (cl-ppcre::create-scanner "\\s*prefix1\\s*prefix2\\s*(\\w[\\w\\d_]*)\\s*\\(\\s*([^\\)]*\\))\\s*;\\s*"))
(defparameter *filename* "c:/pva/home/test.txt")
(defun read-txt-without-comments (file-name)
"Would epically fail in case the file format changes, because currently it expects
the \"/*\" and \"*/\" sequences to be on the separate line."
(let ((fstr (make-array '(0) :element-type 'base-char :fill-pointer 0 :adjustable t)))
(with-output-to-string (s fstr)
(let ((comment nil))
(with-open-file (input-stream file-name :direction :input)
(do ((line (read-line input-stream nil 'eof) (read-line input-stream nil 'eof)))
((eql line 'eof))
(multiple-value-bind (start-comment-from)
(cl-ppcre:scan ".*/\\*" line)
(multiple-value-bind (end-comment-from)
(cl-ppcre:scan ".*\\*/" line)
(if start-comment-from
(setf comment t))
(if (not comment)
(format s "~A~%" line))
(if end-comment-from
(setf comment nil))))))))
fstr))
(let* ((string (read-txt-without-comments "c:/pva/home/test.txt")))
(multiple-value-bind (a b c d) (cl-ppcre::scan *name-and-parameters-list* string)
(format t "~a ~a ~a ~a~%|~a|~%|~a|~%"
a b c d
(subseq string (svref c 0) (svref c 1))
(subseq string (svref d 0) (svref d 1)))))
添加 3: 完整的输入:
prefix1 prefix2 name1(
type1 name1,
type2 name2
);
prefix1 prefix2 name2( type3 name1, type2 name2 );
最佳答案
这适用于我最近的 cl-ppcre
正如您所期望的那样:
(cl-ppcre:register-groups-bind (name argument)
("\\s*prefix1\\s*prefix2\\s*(\\w[\\w\\d_]*).*\\(\\s*([^\\)]*\\))\\s*;\\s*"
"prefix1 prefix2 name1(
type1 name1,
type2 name2
);" :sharedp t)
(list name argument))
("name1" "type1 name1,
type2 name2
)")
也许,显示更多的代码?
关于regex - 使用 cl-ppcre 的正则表达式匹配错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17040456/