为什么在Java Regex中需要两个斜杠才能找到“+” symobl? [英] Why do I need two slashes in Java Regex to find a "+" symobl?

查看:107
本文介绍了为什么在Java Regex中需要两个斜杠才能找到“+” symobl?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是一些我不明白背后的全部意义。我明白,如果我想使用正则表达式找到它,我需要逃避任何特殊的意义。而且我还读到某个地方,如果它在一个字符串文字里面,你需要在Java中转义反斜杠。我的问题是,如果我逃避反斜杠,它不会失去意义吗?那么它将无法逃避以下加号?



抛出一个错误(但是不应该这样工作,因为那是如何逃脱这些特殊字符?) :

  replaceAll(\ + \s,)); 

作品:

 code> replaceAll(\\ + \\\s,)); 

希望这是有道理的。我只是想了解为什么我需要这些额外的斜杠的功能,当我正在阅读的正则表达式教程不提及它们。而\ +之类的东西应该会找到加号。

解决方案

p>这里有两个逃脱。第一个反斜杠是为了转义Java语言的第二个反斜杠,以创建一个实际的反斜杠字符。反斜杠字符是正则表达式引擎解释的 + s 。这就是为什么你需要两个反斜杠 - 一个用于Java,一个用于正则表达式引擎。只有一个反斜杠,Java将 \s \ + 作为非法转义字符报告 - 不适用于正则表达式,但对于Java语言中的实际字符。


Just something I don't understand the full meaning behind. I understand that I need to escape any special meaning characters if I want to find them using regex. And I also read somewhere that you need to escape the backslash in Java if it's inside a String literal. My question though is if I "escape" the backslash, doesn't it lose its meaning? So then it wouldn't be able to escape the following plus symbol?

Throws an error (but shouldn't it work since that's how you escape those special characters?):

replaceAll("\+\s", ""));

Works:

replaceAll("\\+\\s", ""));

Hopefully that makes sense. I'm just trying to understand the functionality behind why I need those extra slashes when the regex tutorials I've read don't mention them. And things like "\+" should find the plus symbol.

解决方案

There are two "escapings" going on here. The first backslash is to escape the second backslash for the Java language, to create an actual backslash character. The backslash character is what escapes the + or the s for interpretation by the regular expression engine. That's why you need two backslashes -- one for Java, one for the regular expression engine. With only one backslash, Java reports \s and \+ as illegal escape characters -- not for regular expressions, but for an actual character in the Java language.

这篇关于为什么在Java Regex中需要两个斜杠才能找到“+” symobl?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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