Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
381 views
in Technique[技术] by (71.8m points)

regex - Regular expression, match substring between pipes

I want to extract/match substrings/sizes in the following string "|XS|XL|S|M|" using regular expression. In this particular case, XS, XL, S and M.

I have tried the following regular expressions without success.

|(w+)|

Matches: XS, S

(?=.(w+)) 

Matches: XS, S, XL, L, S, M

question from:https://stackoverflow.com/questions/65920340/javascript-regex-to-match-everything-between-two-pipes

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You problem with the first match is that is consumes the pipes, so they are not there for the next match.

The second pattern is a little convoluted but what you are saying is for each character in the string grab all word characters that follow it, without consuming them. So at the first pipe that is XS, the engine then moves to the X where the answer is S. The engine then moved to the S where the pattern doesn't match.

You need to use positive lookaround, so you match and consume the text between pipes without consuming the pipes. You want to, for any group of word characters, assert that it has a pipe preceding and following it. In which case, you want to consume it.

If your language supports it (You don't mention which regex engine you are using) this pattern will work:

(?<=|)[^|]++(?=|)
  • (?<=|) asserts that there is a pipe behind the pattern
  • [^|]++ possessively matches all non-pipe characters
  • (?=|) asserts that there is a pipe following the pattern

Here is a testcase in Java (ignore the \, there are just Java syntax):

public static void main(String[] args) throws Exception {
    final String test = "|XS|XL|S|M|";
    final Pattern pattern = Pattern.compile("(?<=\|)[^|]++(?=\|)");
    final Matcher matcher = pattern.matcher(test);
    while(matcher.find()) {
        System.out.println(matcher.group());
    }
}

Output:

XS
XL
S
M

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...