Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

regex - Replace all instances of a character within context

The below is an example of a very large text file that I have:

@Don't replace this line: <http://nomatch.com#>
/or this line!/

<http://example.com#Example/Replace/With/Underscores> and <http://example.com#Example/Replace/With/Underscores2> 

</Nothing to replace on this line either./>

I would like to replace all instances of / (forward slash) on each line after <http://example.com#Example/ and before >. Therefore, the resulting file should look like:

@Don't replace this line: <http://nomatch.com#>
/or this line!/

<http://example.com#Example_Replace_With_Underscores> and <http://example.com#Example_Replace_With_Underscores>

</Nothing to replace on this line either./>

So far I have come up with the regex: (?=.*?>)/, but this is grabbing every / on a line with a > (link to example). At the moment I'm using VSCode to perform the find and replace.

question from:https://stackoverflow.com/questions/65948959/replace-all-instances-of-a-character-within-context

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use

(?<=<http://example.com#Example/[^>]*)/(?=[^>]*>)

See the regex demo. Details:

  • (?<=<http://example.com#Example/[^>]*) - a positive lookbehind that makes there is a <http://example.com#Example/ string followed with any zero or more chars other than > as many as possible immediately to the left of the current location
  • / - a / char
  • (?=[^>]*>) - a positive lookahead (if you need to make sure there is a closing >) that makes there there are zero or more chars other than > and then a > char immediately to the right of the current location.

See Visual Studio Code demo and settings:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...