简体   繁体   English

正则表达式匹配“ | ”

[英]Regular Expression to Match “ | ”

I am trying to use Java's useDelimiter method on it's Scanner class to do some simple parsing.我试图在它的Scanner类上使用 Java 的useDelimiter方法来做一些简单的解析。 Basically each line is a record delimited by " | ", so for example:基本上每一行都是一个由“|”分隔的记录,例如:

2 | John Doe
3 | Jane Doe
4 | Jackie 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!谢谢,我真的很感激!

I came up with \\s\\|\\s which in Java would be expressed as "\\\\s\\\\|\\\\s" .我想出了\\s\\|\\s在 Java 中将表示为"\\\\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 :)我不需要任何硬核,只需要一些有用的东西,这似乎是:)

Sorry for answering my own question, I guess after typing it out it helped me think.很抱歉回答我自己的问题,我想在输入后它帮助我思考。

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 | Jackie 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 Jackie Chan
" \| " 

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

Dont forget to include the * to match repeating character不要忘记包含 * 以匹配重复字符

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

Edited -- You can use simply this too .*\\|.*编辑 - 你也可以简单地使用这个.*\\|.*

......

^[ \| ]?$

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

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