clojure - 如果找到字符串“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 个字符的值,如果有行尾,它也应该工作。
解决方案
你可以使用这个:
(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
推荐阅读
- azure - 使用 Nativescript Core 将图像上传到 Azure 博客
- ruby - rbenv 安装 2.2.1 构建失败 Ubuntu 16.04
- android - OAuth 2 客户端 ID 重复问题
- ruby-on-rails - 在生产中通过浏览器连接到应用程序地址
- sql - SQL 子字符串 charindex
- spring-rabbit - 使用带有rabbit mq流的spring cloud任务时出错
- php - 如何通知 Zend 3 控制器有关 MVC 错误事件?
- docker - CentOS 7.5 上是否提供 docker 存储驱动程序 overlay2 生产?
- c# - 字典列表只保留最后一行
- python - 如何读取保存的图像并将其定位在没有任何扭曲的坐标中?