Search code examples
regexclassificationbuilderrule

Regular expression to divide a|b|c


Have to divide tracking code of varying length a|b|c or a|b|c|d

I always want 'a' to go to 'Name' 'b' to go to 'ID' 'c' to go to 'Title'

So have set up the below rule

#   Select Rule Type    Enter Match Criteria    Set Classification  To
1   Regular Expression  ^(.+)\|(.+)\|(.+)$  Name            $1
2   Regular Expression  ^(.+)\|(.+)\|(.+)$  ID              $2
3   Regular Expression  ^(.+)\|(.+)\|(.+)$  Title           $3

This works fine for a|b|c, however for varying length like a|b|c|d result is not correct and comes as follows:--

'a|b' to 'Name' 'c' to 'ID' 'd' to 'Title'

Can you suggest how to fix this so that the result for a|b|c|d comes as

a' to go to 'Name' 'b' to go to 'ID' 'c|d' to 'Title'


Solution

  • You should try this one that is working for 1 to N elemnts in your list.

    [^\|]+?[^\|]*
    

    You can also try it in this DEMO.

    EDIT: According to your need I suggest this regex:

    (.*?)\|(.*?)\|(.*)
    

    You can also take a look at the DEMO.

    Quick explanation from here: The .+? part is the un-greedy version of .+ (one or more of anything). When we use .+, the engine will basically match everything. Then, if there is something else in the regex it will go back in steps trying to match the following part. This is the greedy behavior, meaning as much as possible to satisfy.

    When using .+?, instead of matching all at once and going back for other conditions (if any), the engine will match the next characters by step until the subsequent part of the regex is matched (again if any). This is the un-greedy, meaning match the fewest possible to satisfy.