Java - 正则表达式,用于匹配反斜杠后跟引号 [英] Java - regular expression to match a backslash followed by a quote

查看:460
本文介绍了Java - 正则表达式,用于匹配反斜杠后跟引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何编写正则表达式来匹配此 \(反斜杠然后引用)?
假设我有一个这样的字符串:

How to write a regular expression to match this \" (a backslash then a quote)? Assume I have a string like this:

<a href=\"google.com\"> click to search </a>

我需要用<替换所有 \ code>,结果如下:

I need to replace all the \" with a ", so the result would look like:

<a href="google.com"> click to search </a>

这个不起作用: str.replaceAll(\\\,\)因为它只匹配报价。不知道如何绕过反斜杠。我可以先删除反斜杠,但我的字符串中还有其他反斜杠。

This one does not work: str.replaceAll("\\\"", "\"") because it only matches the quote. Not sure how to get around with the backslash. I could have removed the backslash first, but there are other backslashes in my string.

推荐答案

如果要替换文字和 不需要正则表达式语法 而不是 replaceAll 使用替换

If you are replacing literals and don't need regex syntax instead of replaceAll use replace

str = str.replace("\\\","\"");

这两种方法都将取代所有次目标,但 replace 将按字面意思处理目标。

Both methods will replace all occurrences of targets, but replace will treat targets literally.

但如果你真的 必须 使用正在寻找的正则表达式

BUT if you really must use regex you are looking for

str = str.replaceAll("\\\\\"", "\"")

\ 是正则表达式中的特殊字符(例如用于创建 \d - 表示数字的字符类)。要使正则表达式处理 \ 作为普通字符,您需要在它之前放置另一个 \ 来关闭它的特殊含义(你需要逃避它)。我们试图创建的正则表达式是 \\

\ is special character in regex (used for instance to create \d - character class representing digits). To make regex treat \ as normal character you need to place another \ before it to turn off its special meaning (you need to escape it). So regex which we are trying to create is \\.

但要创建代表 \\ 的字符串,这样你就可以把它传递给regex引擎你需要写它四个 \ \\\\),因为 \ 也是String中的特殊字符(例如,它可以用作 \t 来表示制表符),所以你还需要同时转义 \ 那里。

But to create string representing \\ so you could pass it to regex engine you need to write it as four \ ("\\\\"), because \ is also special character in String (it can be used for instance as \t to represent tabulator) so you also need to escape both \ there.

换句话说,你需要逃避 \ 两次:

In other words you need to escape \ twice:


  • 一次在正则表达式 \\

  • 一次在String \\\\

  • once in regex \\
  • and once in String "\\\\"

这篇关于Java - 正则表达式,用于匹配反斜杠后跟引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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