Regex Match all characters between two strings

2018-12-31 04:06发布

Example: "This is just\na simple sentence".

I want to match every character between "This is" and "sentence". Line breaks should be ignored. I can't figure out the correct syntax.

标签: regex
11条回答
不再属于我。
2楼-- · 2018-12-31 04:17

For example

(?<=This is)(.*)(?=sentence)

Regexr

I used lookbehind (?<=) and look ahead (?=) so that "This is" and "sentence" is not included in the match, but this is up to your use case, you can also simply write This is(.*)sentence.

The important thing here is that you activate the "dotall" mode of your regex engine, so that the . is matching the newline. But how you do this depends on your regex engine.

The next thing is if you use .* or .*?. The first one is greedy and will match till the last "sentence" in your string, the second one is lazy and will match till the next "sentence" in your string.

Update

Regexr

This is(?s)(.*)sentence

Where the (?s) turns on the dotall modifier, making the . matching the newline characters.

Update 2:

(?<=is \()(.*?)(?=\s*\))

is matching your example "This is (a simple) sentence". See here on Regexr

查看更多
骚的不知所云
3楼-- · 2018-12-31 04:21

use this: (?<=beginningstringname)(.*\n?)(?=endstringname)

查看更多
柔情千种
4楼-- · 2018-12-31 04:23

for a quick search in VIM, you could use at Vim Control prompt: /This is.*\_.*sentence

查看更多
梦寄多情
5楼-- · 2018-12-31 04:24

This:

This is (.*?) sentence

works in javascript.

查看更多
千与千寻千般痛.
6楼-- · 2018-12-31 04:25

You can simply use this: \This is .*? \sentence

查看更多
宁负流年不负卿
7楼-- · 2018-12-31 04:29

I landed here on my search for regex to convert this print syntax between print "string", in Python2 in old scripts with: print("string"), for Python3. Works well, otherwise use 2to3.py for additional conversions. Here is my solution for others:

Try it out on Regexr.com (doesn't work in NP++ for some reason):

find:     (?<=print)( ')(.*)(')
replace: ('$2')

for variables:

(?<=print)( )(.*)(\n)
('$2')\n

for label and variable:

(?<=print)( ')(.*)(',)(.*)(\n)
('$2',$4)\n

How to replace all print "string" in Python2 with print("string") for Python3?

查看更多
登录 后发表回答