如果找到字符串“ john”,则将一个包含数据并在其前后打印10个字符的打印值读入一个新文件

时间:2019-07-01 11:47:29

标签: clojure

无论何时遇到“ 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个字符的值,并且如果有行尾,它也应该工作。

1 个答案:

答案 0 :(得分:0)

您可以使用此:

Vaccum

更新1-重叠模式

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

(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")

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

(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"])