2

Hello I want to replace a string in a file but in a special way.

For example I'm searching for a string like " hideMenu()" by using the regex #"\WhideMenu\W" so that it will not return some text where hideMenu is inside like "willHideMenu()".

Well I'm using the replace function like this:

(clojure.string/replace textFile #"\WhideMenu\W" "hideMenu2")

But the problem is that it now replaces the first whitespace and last character of the textfile too.

For example if there is:

function hideMenu() 

it will be:

functionhideMenu2)

Which is pretty logical but how do I use replace without loosing the first and last character? I want as result:

function hideMenu2()

2 Answers 2

3

If clojure supports it, use lookahead and behind Regex:

(clojure.string/replace textFile #"(?<=\W)hideMenu(?=\W)" "hideMenu2")

otherwise you might need to match the character and use it in the replacement:

(clojure.string/replace textFile #"(\W)hideMenu(\W)" "$1hideMenu2$2")
Sign up to request clarification or add additional context in comments.

2 Comments

the second solution looks like that it works real good for my problem.
@Kingalione Note that these two solutions won't work for hideMenu directly at the beginning or end of the file. It might be irrelevant for your specific use case but it's something to keep in mind.
3

\W matches non-word characters and ( is one of them. What you probably want is a word-boundary match, expressed as \b:

(clojure.string/replace "hideMenu()" #"\bhideMenu\b" "hideMenu2")
;; => "hideMenu2()"

1 Comment

Another option is using capturing groups in the replacement. $0 is the whole of the capture, $1 the first capturing group, $2 the second etc. So (clojure.string/replace "function hideMenu() " #"\b(hideMenu)\b" "$12"). => "function hideMenu2() ". In this case it might be irrelevant since boundaries aren't captured, but it might be worth mentioning.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.