将管道插入 Java 模式表达式的正确方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1433115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 12:03:09  来源:igfitidea点击:

What is the proper way of inserting a pipe into a Java Pattern expression?

javaregex

提问by TheOne

What is the proper way of inserting a pipe into a Java Pattern expression?

将管道插入 Java 模式表达式的正确方法是什么?

I actually want to use a pipe as a delimiter and not the or operator.

我实际上想使用管道作为分隔符而不是 or 运算符。

I.E:

IE:

"hello|world".split("|"); --> {"hello", "world"}

采纳答案by newacct

in Java 1.5+:

在 Java 1.5+ 中:

"hello|world".split(Pattern.quote("|"));

回答by TheOne

"hello|world".split("\\|"); --> {"hello", "world"}

First set of "\\"only yields the \ as the delimiter. Therefore 2 sets are needed to escape the pipe.

第一组"\\"只产生 \ 作为分隔符。因此需要 2 套才能脱离管道。

回答by Kevin

Escape it with \\:

\\转义它:

"hello|world".split("\|");

回答by Hank Gay

I have this problem a lot (encoding a regex into a Java String), so I have bookmarked the regex tool at fileformat.info; it has a nifty function where it will show you the Java Stringrepresentation of a regex after you test it.

我经常遇到这个问题(将正则表达式编码为 Java String),所以我在 fileformat.info 中正则表达式工具添加了书签;它有一个漂亮的函数,它会String在你测试之后向你显示正则表达式的 Java表示。