java 匹配“|”的正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2376166/
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-10-29 20:50:54  来源:igfitidea点击:

Regular Expression to Match " | "

javaregexparsingjava.util.scannerdelimiter

提问by Jorge Israel Pe?a

Hey guys, I am trying to use Java's useDelimitermethod on it's Scannerclass to do some simple parsing. Basically each line is a record delimited by " | ", so for example:

嘿伙计们,我试图useDelimiter在它的Scanner类上使用 Java 的方法来做一些简单的解析。基本上每一行都是一个由“|”分隔的记录,例如:

2 | John Doe
3 | Jane Doe
4 | Hymanie Chan

The method takes as a parameter a regular expression for which to match for. Can someone please provide me with the regular expression that would match |(A vertical bar separated by one space on both sides).

该方法将要匹配的正则表达式作为参数。有人可以为我提供匹配的正则表达式吗|(两边用一个空格分隔的竖线)。

Thanks, I would really appreciate it!

谢谢,我真的很感激!

回答by Jorge Israel Pe?a

I came up with \s\|\swhich in Java would be expressed as "\\s\\|\\s". I don't know if this is the best one though. I don't need anything hardcore, just something that works, and this seems to :)

我想出了\s\|\s在 Java 中将表示为"\\s\\|\\s". 我不知道这是否是最好的。我不需要任何硬核,只需要一些有用的东西,这似乎是:)

Sorry for answering my own question, I guess after typing it out it helped me think.

很抱歉回答我自己的问题,我想在输入后它帮助我思考。

回答by Olivier Croisier

Here is a code snippet that parses a string (or a whole File, Scanner accepts both), and extracts the number and name from each line :

这是一个解析字符串(或整个文件,Scanner 接受两者)并从每一行中提取数字和名称的代码片段:

String s = 
    "1 | Mr John Doe\n" + 
    "2 | Ms Jane Doe\n" + 
    "3 | Hymanie Chan\n";

Pattern pattern = Pattern.compile("(\d+) \| ((\w|\s)+)");
Scanner scan = new Scanner(s);
while (scan.findInLine(pattern) != null) {
    MatchResult match = scan.match();

    // Do whatever appropriate with the results
    System.out.printf("N° %d is %s %n", Integer.valueOf(match.group(1)), match.group(2));

    if (scan.hasNextLine()) {
        scan.nextLine();
    }
}

This code snippet produces the following result :

此代码片段产生以下结果:

N° 1 is Mr John Doe
N° 2 is Ms Jane Doe
N° 3 is Hymanie Chan

回答by adhanlon

" \| " 

would work, you need to escape quotes and the |

会工作,你需要转义引号和 |

回答by Fadrian Sudaman

Dont forget to include the * to match repeating character

不要忘记包含 * 以匹配重复字符

\S*\s*\|\s*[\S\t ]*

Edited -- You can use simply this too .*\|.*

已编辑-您也可以简单地使用它 .*\|.*

回答by Sarfraz

......

......

^[ \| ]?$