Regular expression to match "|"

Hi guys, I am trying to use the Java useDelimiter method for this Scanner class to do a simple parsing. Basically, each line represents an entry limited by the symbol "|", for example, for example:

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

The method takes as a parameter the regular expression for which to match. Can someone please provide me a regex that matches | (vertical strip divided by one space on both sides).

Thank you, I would really appreciate it!

+6
java java.util.scanner regex parsing delimiter
source share
5 answers

I came up with \s\|\s , which in Java will be expressed as "\\s\\|\\s" . I do not know if this is the best. I don’t need anything hardcore, just something works, and it seems :)

Sorry for the answer to my own question, I think, after entering it, it helped me to think.

+11
source share

Here is a piece of code that analyzes the line (or the entire file, the scanner accepts both) and extracts the number and name from each line:

 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 piece of code gives the following result:

 1 is Mr John Doe N° 2 is Ms Jane Doe N° 3 is Jackie Chan 
+3
source share
 " \| " 

will work, you need to avoid quotes and |

0
source share

Do not forget to include the * symbol with the repeated symbol

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

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

0
source share

......

 ^[ \| ]?$ 
0
source share

All Articles