Regex Matching a string

128 views Asked by At

I currently am writing a regex to match strings such as this:

( expr ) | id | num
term * factor | factor
expr

I want the regex to match each occurence of set of characters between each ' | ', but also match solo expressions such as:

expr

I currently have this, but I am doing my negative lookahead wrong and I am not really sure how to proceed.

((.*) \|) (.*)$

P.s. I am not really fond of using .* in this situation, but I cannot think of another way to match, because the characters between ' | 's can be word characters, digits, or anything in between.

EDIT:

I would like the output matches to look like this:

Regex ran on line 1, output:

3 matches - ( expor ), id, num

Regex ran on line 2:

2 matches - term * factor, factor

Regex ran on line 3:

1 match - expr
1

There are 1 answers

0
LeonidasCZ On BEST ANSWER

This could be your simple regex:

[^|]+

-capture one or more characters until you reach "|" (or end of string)

Or alternatively you could use String.split("|");

String line = "term * factor | factor";
String[] split = line.split("\\|");