忽略正则表达式中的换行符? [英] Ignoring the line break in regex?

查看:1635
本文介绍了忽略正则表达式中的换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在文字文件中有以下内容

I have below content in text file

  some texting content <img  src="cid:part123" alt=""> <b> Test</b>

我从文件中读取它并将其存储在String中,即inputString

I read it from file and store it in String i.e inputString

   expectedString = inputString.replaceAll("\\<img.*?cid:part123.*?>",
    "NewContent");

我得到预期的产出即

     some texting content NewContent <b> Test</b>

基本上如果img和src之间有行尾字符,如下所示,它不起作用以下示例

Basically if there is end of line character in between img and src like below, it does not work for example below

 <img  
          src="cid:part123" alt="">

在匹配时,有没有办法正则表达式忽略行间字符?

Is there a way regex ignore end of line character in between while matching?

推荐答案

如果您希望点(。)匹配换行符另外,你可以使用 Pattern.DOTALL 标志。另外,在 String.replaceAll()的情况下,你可以在开头的时候添加一个(?s)。 pattern,相当于这个标志。

If you want your dot (.) to match newline also, you can use Pattern.DOTALL flag. Alternativey, in case of String.replaceAll(), you can add a (?s) at the start of the pattern, which is equivalent to this flag.

来自 Pattern.DOTALL - JavaDoc : -

From the Pattern.DOTALL - JavaDoc : -


Dotall 模式也可以通过嵌入式标志表达式(?s)启用。
s 是单行模式的助记符,这就是Perl中调用的
。)

Dotall mode can also be enabled via the embedded flag expression (?s). (The s is a mnemonic for "single-line" mode, which is what this is called in Perl.)

因此,您可以像这样修改您的模式: -

So, you can modify your pattern like this: -

expectedStr = inputString.replaceAll("(?s)<img.*?cid:part123.*?>", "Content");

注意: - 您无需逃避尖括号(<)

这篇关于忽略正则表达式中的换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆