java正则表达式引号,Java,在正则表达式中转义(使用)引号

I'm trying to use the following regex in Java, that's supposed to match any lang="2-char-lang-name":

String lang = "lang=\"" + L.detectLang(inputText) +"\"";

shovel.replaceFirst("lang=\"[..]\"", lang);

I know that a single slash would be interpreted by regex as a slash and not an escape character (so my code doesn't work), but if I escape the slash, the " won't be escaped any more and I'd get a syntax error.

In other words, how can I include a " in the regex? "lang=\\"[..]\\"" won't work. I've also tried three slashes and that didn't have any matches either.

I am also aware of the general rule that you don't use regex to parse XML/HTML. (and shovel is an XML) However, all I'm doing is, looking for a lang attribute that is within the first 30 characters of the XML, and I want to replace it. Is it really a bad idea to use regex in this case? I don't think using DOM would be any better/more efficient.

解决方案

Three slashes would be correct (\\ + \" becomes \ + " = \"). (Update: Actually, it turns out that isn't even necessary. A single slash also works, it seems.) The problem is your use of [..]; the [] symbols mean "any of the characters in here" (so [..] just means "any character").

Drop the [] and you should be getting what you want:

String ab = "foo=\"bar\" lang=\"AB\"";

String regex = "lang=\\\"..\\\"";

String cd = ab.replaceFirst(regex, "lang=\"CD\"");

System.out.println(cd);

Output:

foo="bar" lang="CD"

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JavaScript正则表达式Java正则表达式在语法上有一些差异,但是它们的基本概念和用法是相似的。下面是将JavaScript正则表达式转换为Java正则表达式的一些常见规则: 1. 语法差异: - JavaScript正则表达式使用斜杠(/)作为定界符,而Java正则表达式使用引号(")作为定界符。 - JavaScript正则表达式的特殊字符需要进行转义,而Java正则表达式的特殊字符不需要转义。 2. 字符类: - JavaScript正则表达式的字符类使用方括号([])表示,而Java正则表达式使用方括号([])或者Unicode转义(\p{...})表示。 - JavaScript正则表达式的字符类可以使用连字符(-)表示范围,而Java正则表达式需要使用Unicode转义(\uXXXX)表示范围。 3. 量词: - JavaScript正则表达式的量词使用花括号({})表示,而Java正则表达式使用花括号({})或者问号(?)表示。 - JavaScript正则表达式的贪婪量词默认是贪婪模式,而Java正则表达式的贪婪量词需要在后面添加问号(?)来表示非贪婪模式。 4. 边界匹配: - JavaScript正则表达式的边界匹配使用插入符号(^)和美元符号($)表示,而Java正则表达式使用\A和\Z表示。 5. 其他差异: - JavaScript正则表达式的捕获组使用圆括号(())表示,而Java正则表达式使用圆括号(())或者方括号([])表示。 - JavaScript正则表达式的反向引用使用反斜杠加数字(\1、\2等)表示,而Java正则表达式使用美元符号加数字($1、$2等)表示。 以上是一些常见的JavaScript正则表达式转换为Java正则表达式的规则。具体转换时,还需要根据具体的正则表达式进行适当的调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值