How do I match any character across multiple lines

2018-12-31 00:14发布

For example, this regex

(.*)<FooBar>

will match:

abcde<FooBar>

But how do I get it to match across multiple lines?

abcde
fghij<FooBar>

20条回答
梦寄多情
2楼-- · 2018-12-31 00:42

we can also use

(.*?\n)*?

to match everything including newline without greedy

This will make the new line optional

(.*?|\n)*?
查看更多
后来的你喜欢了谁
3楼-- · 2018-12-31 00:43

It depends on the language, but there should be a modifier that you can add to the regex pattern. In PHP it is:

/(.*)<FooBar>/s

The s at the end causes the dot to match all characters including newlines.

查看更多
高级女魔头
4楼-- · 2018-12-31 00:43

"." normally doesn't match line-breaks. Most regex engines allows you to add the S-flag (also called DOTALL and SINGLELINE) to make "." also match newlines. If that fails, you could do something like [\S\s].

查看更多
流年柔荑漫光年
5楼-- · 2018-12-31 00:44

Use RegexOptions.Singleline, it changes the meaning of . to include newlines

Regex.Replace(content, searchText, replaceText, RegexOptions.Singleline);

查看更多
还给你的自由
6楼-- · 2018-12-31 00:45

I had the same problem and solved it in probably not the best way but it works. I replaced all line breaks before I did my real match:

mystring= Regex.Replace(mystring, "\r\n", "")

I am manipulating HTML so line breaks don't really matter to me in this case.

I tried all of the suggestions above with no luck, I am using .Net 3.5 FYI

查看更多
何处买醉
7楼-- · 2018-12-31 00:45

I wanted to match a particular if block in java

   ...
   ...
   if(isTrue){
       doAction();

   }
...
...
}

If I use the regExp

if \(isTrue(.|\n)*}

it included the closing brace for the method block so I used

if \(!isTrue([^}.]|\n)*}

to exclude the closing brace from the wildcard match.

查看更多
登录 后发表回答