Regex match closest term

牧云@^-^@ 提交于 2020-01-06 19:36:52

问题


For the below paragraph, I am going to paste it into Notepad++ and use the Count functionality to find the count of "test of foo bar.\r\nThis is a" I know I can do this using the "Extended" Search mode but my real life scenario requires regex.

test of reg ex
This is a test of foo bar
This is a
test foo
This is a test of foo bar
This is a
test foo
This is a test of foo bar
This is a
test foo

In plain English, I am trying to

  1. Find location of "This is a"
  2. Back track and stop at the first instance of the word test.

I am not too sure how to word the title, I'll modify it later

How about this? with random a1-f3 texts

test of d1
test of e2
test of f3
This is a test of a1
This is a
test foo.
This is a test of b2
This is a
test foo.
This is a test of c3
This is a
test foo.

Also would like to use the s modifier since notepad++'s . matches newline uses the s modifier. I almost have what I need in the below screen cap except for the first match, it matches too much.

sample text, http://pastebin.com/xKJa8ECe

What I have now, which over matches


回答1:


test of foo bar[\s\S]*?This is a

You can use this.See demo.

https://regex101.com/r/uF4oY4/48




回答2:


Try this regex:

test of .{2}\s+This is a

Don't forget to uncheck the option . matches newline. (Alt + .)

Tested on Notepad 6.7.8.2




回答3:


By your definition, shouldn't more text be selected, like this:

test of d1
test of e2
test of f3
This is a test of a1
This is a test foo.
This is a test of b2
This is a test foo.
This is a test of c3
This is a
test foo.

But anyways, since you're only counting, you can use this:

.test of.*?\nThis is a

to match what you wanted (including one character before the word test since it seems like you don't want any 'test' that begin a line

test of d1
test of e2
test of f3
This is a test of a1
This is a
test foo.
This is a test of b2
This is a
test foo.
This is a test of c3
This is a
test foo.

EDIT: Not using '.':

 test of(\S|\s)*?This is a


来源:https://stackoverflow.com/questions/32050410/regex-match-closest-term

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!