I am currently using this following regular expression to split my String into groups.^([a-zA-Z0-9]*)(\[([a-zA-Z0-9=]*)\]){0,1}@([a-zA-Z0-9]*)$Pty[R=4]@IDI am getting four groups1) Pty2) [R=4]3) R=44) IDBut, I need only three groups1) Pty2) R=43) IDThis regular expression should be also be able to accept Pty@ID to get two groups1) Pty2) IDHow can I achieve this?
How can I parse my String using regular expression to get only certain number of matches?
regular expression
You don't specify any tools, so I use perl as example:$ echo Pty[R=4]@ID | perl -nle '    print $1\n$2\n$3\n$4        if /^([a-zA-Z0-9]*)(\[([a-zA-Z0-9=]*)\]){0,1}@([a-zA-Z0-9]*)$/'Pty[R=4]R=4ID$ echo Pty@ID | perl -nle '    print $1\n$2\n$3\n$4        if /^([a-zA-Z0-9]*)(\[([a-zA-Z0-9=]*)\]){0,1}@([a-zA-Z0-9]*)$/'PtyIDWith regular expression capture group, you can use backreferences to get the previous matches. In perl, you can use $1, $2,...,$n.In your case, you can use a non-capturing group to prevent [R=4] from being captured:$ echo Pty[R=4]@ID |perl -nle '    print $1\n$2\n$3        if /^([a-zA-Z0-9]*)(?:\[([a-zA-Z0-9=]*)\]){0,1}@([a-zA-Z0-9]*)$/'PtyR=4IDAs you mentioned php in your comment, you can use php backreference syntax \1 or \g1 or \g{1}.