我正在使用Clojure来解析和分析XML文件 这是一个示例:
BSS:17,NSVC:1
BSS:17,NSVC:4
BSS:17,NSVC:5
BSS:17,BTSM:0,BTS:3
BSS:17,BTSM:0,BTS:4
BSS:17,BTSM:0,BTS:5
BSS:17,BTSM:1,BTS:0
BSS:17,BTSM:1,BTS:1
BSS:17,BTSM:1,BTS:2
BSS:17,BTSM:1,BTS:3
我对最后一个值感兴趣(最后一个逗号后的值,但在最后一个逗号之前:在我的情况下是NSVS和BTS),它们之后的数字无关紧要。
如何提取前一个字符串中的最后一个值?
答案 0 :(得分:3)
您可以使用此功能处理各个行:
(defn lastval [s]
(second (re-find #",([^,:]+):\d*$" s)))
; ^ the comma preceding the interesting section
; ^ the part in parens will be captured as a group
; ^ character class meaning "anything except , or :"
; ^ the colon after the interesting section
; ^ any number of digits after the colon
; ^ end of string
; ^ returns a vector of [part-that-matches, first-group];
; we're interested in the latter, hence second
NB。如果正则表达式不匹配,则返回nil
。
E.g:
user> (lastval "BSS:17,BTSM:0,BTS:3")
"BTS"
如果您以后想要在易于使用的位中提取所有信息,可以使用
(defn parse [s]
(map (juxt second #(nth % 2)) (re-seq #"(?:^|,)([^,:]+):(\d+)" s)))
E.g。
user> (parse "BSS:17,BTS:0,BTS:3")
(["BSS" "17"] ["BTS" "0"] ["BTS" "3"])
答案 1 :(得分:0)
您可以使用lastIndexOf查找最后一个逗号吗?
答案 2 :(得分:0)
这对你有用吗?
(def tmp (str "BSS:17,NSVC:1\n
BSS:17,NSVC:4\n
BSS:17,NSVC:5\n
BSS:17,BTSM:0,BTS:3\n
BSS:17,BTSM:0,BTS:4\n
BSS:17,BTSM:0,BTS:5\n
BSS:17,BTSM:1,BTS:0\n
BSS:17,BTSM:1,BTS:1\n
BSS:17,BTSM:1,BTS:2\n
BSS:17,BTSM:1,BTS:3\n"))
(defn split [s sep]
(->> (.split s sep)
seq
(filter #(not (empty? %)))))
(reduce (fn[h v]
(conj h (last v)))
[] (map #(split % ",")
(split tmp "\n")))
我假设线之间有某种分隔符。