Search code examples
c++regexboost-regex

Regular expressions in C++


Right now I have two regular expressions that does this:

Regex-1 = "(\\{(\\w+)\\})";
Regex-2 = "(\\{([^\\|]*)\\|([^\\|]*)\\|([^\\|]*)\\})"; 

I just want to be able to combine the two Regex into one, so that which ever Regex searches first will be the match.

Conceptually i'm thinking regex-1 || regex-2. Is that possible to combine them?

Thanks.


Solution

  • You mean like this?

    Regex-1_2 = "(\\{(\\w+)\\})|(\\{([^\\|]*)\\|([^\\|]*)\\|([^\\|]*)\\})";
    

    EDIT:

    So, something like this?

    {(((\w+)|({\w+}))\|?)*}
    

    EDIT 2:

    Your last comment helps. So, work from beginning to end. You know you want to match an opening curly bracket, so that part is easy:

    {
    

    Now, after the first curly bracket, there are two options. Either there will be one or more alphanumeric (or underscore) characters, or there will be three groups of zero or more characters separated by pipes. The first two groups must be non-pipe characters, while the last group must be non-curly bracket characters (since a curly bracket will close the expression). That can be expressed using the alternation construct:

    {(\w+|[^|]*\|[^|]*\|[^}]*)
    

    Finally, the expression ends with a curly bracket:

    {(\w+|[^|]*\|[^|]*\|[^}]*)}
    

    This works with the example you provided. If your rules are different or more specific, you will need to say so.