문제

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
도움이 되었습니까?

해결책

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("\\|");
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top