简体   繁体   English

如何逃脱Java正则表达式 算子

[英]How to escape java regex | operator

I want to ask something about java regex and hope I will find some help here. 我想问一些有关Java regex的问题,希望在这里能找到一些帮助。

I have a string which looks like "textX|textY|textZ" . 我有一个看起来像"textX|textY|textZ"的字符串。 Now I want to split this on each | 现在,我想在每个| character in java. Java中的字符。

I tried it with 我尝试过

string.split("\|");

but I just get a "Invalid escape sequence" error. 但我只收到"Invalid escape sequence"错误。

How can I split the above string when I use | 我怎么可以拆分上面的字符串时,我使用| as separator? 作为分隔符?

You need double escaping in Java so use: 您需要在Java中进行两次转义,所以请使用:

String[] tokens = string.split("\\|")

OR else use character class: 否则使用字符类:

String[] tokens = string.split("[|]");

you should use \\\\| 您应该使用\\\\| for escaping meta character. 用于转义元字符。

In Java you need to escape characters twice for regex: once for the string, once for the regex. 在Java中,您需要两次对正则表达式转义字符:一次对字符串转义,一次对正则表达式转义。

Try 尝试

string.split("\\|")

You have to use double back slash \\\\ : string.split("\\\\|") . 您必须使用双反斜杠\\\\string.split("\\\\|")

It is because back slash is a escape character for both: java and regex. 这是因为反斜杠是Java和regex的转义字符。 First one escapses the second for java, so that the "real" backslash is passed to regex. 第一个转义第二个转义为Java,以便将“真实”反斜杠传递给regex。

simply doing 简单地做

string.split("\\|");

in java when we escape we do it by two backslashes 在Java中,当我们转义时,我们通过两个反斜杠来实现

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM