首页 > 解决方案 > 如果找到字符串“john”,则读取包含数据的文件并将前后 10 个字符的值打印到新文件中

问题描述

每当遇到“john”时,我需要在字符串“john”之前和之后打印 10 个字符。即使下一行打印了一半的字母,它仍应在前后打印 10 个字符。

我尝试使用 .contains 函数并使用字符串的索引,但是当我输入这样的文件时出现问题:

Hello my name is jo
hn and i work for bla bla.

我尝试了什么:

(ns clojure-assignment.problem6
  (:use [clojure.string :only [index-of]]))

(defn String_manipulation []
  (def str1 (slurp "string.txt"))
  (println str1)
  (def check (.contains str1 "john"))
  (if (= check true)
    (def index (index-of str1 "john")))    
  (println (subs str1 (- index 11) index))
  (println (subs str1 (+ index 4) (+ index  5 10))))

(String_manipulation)

我希望输出在给定字符串之前和之后打印 10 个字符的值,如果有行尾,它也应该工作。

标签: clojure

解决方案


你可以使用这个:

(def s "Hello my name is jo
hn and i work for bla bla.
")

(re-seq #".{10}john.{10}" (str/replace s #"\n" ""))
;; => ("y name is john and i wor")

更新 1 - 重叠模式

如果预计模式会重叠,请使用前瞻正则表达式并从匹配组中提取:

(def s "hello my name is john-john and john is my father's name")

(re-seq #"(?=(.{10}john.{10}))" (str/replace s #"\n" ""))

(["" "y name is john-john and "]
 ["" "e is john-john and john "]
 ["" "-john and john is my fat"])

更新 2 - 打印前缀和后缀匹配组

(use 'clojure.pprint)

(def s "Hello my name is jo
hn and i work for bla bla.
")

(->> (str/replace s #"\n" "")
     (re-seq #"(?=(.{10})john(.{10}))")
     (cl-format *out* "~{~{~a~}~%~}"))
;; => y name is  and i wor



推荐阅读