Replace specific characters in string using regex

Phillip :

So I'm kind of new to regex and would like some help. I have dynamically generated input strings, a sample of which is:

(ACTOR > 0OR(PROC <> NULL AND REVIEW=NULL ANDFERDINAND = NAME ) )

Now I have to replace OR with |, AND with &, = with == and <> with != and provide a space between characters without them.

Normally I could use string.replace() to do this. But, since the statement can come with or without spaces and even since AND can be present in other words as in the case of FERDINAND, i'm finding it a bit difficult.

Expected result:

( ACTOR > 0 | ( PROC != NULL & REVIEW == NULL & FERDINAND == NAME ) )

So I was wondering if someone could help me with this. Thanks in advance..

Donat :

You can try this, but the case ANDFERDINAND cannot be handled. For this a regex is not suitable, because there is no simple criterion for where to separate.

String str2 = str1
      .replaceAll("([0-9])(?=[A-Z])", "$1 ")                 //1
      .replaceAll("\\bAND\\b", "&")                          //2
      .replaceAll("\\bOR\\b", "|")                           //3
      .replaceAll("(?<![=<>!])=(?!=)", "==")                 //4
      .replaceAll("<>", "!=")                                //5
      .replaceAll("(?<=[^&| ])(==|!=|&|\\)|\\|)", " $1")     //6
      .replaceAll("(==|!=|&|\\(|\\)|\\|)(?=[^ &|])", "$1 "); //7

First separate a number followed by a word character (positive look ahead).

Second an third substitute AND and OR at word boundaries.

Fourth substitute =, if it is not part of ==, !=, <= or >= (negative look before and negative look ahead).

Fifth substitute <> (one simple match).

Sixth and seventh make that ==, !=, &, (, ) and | are surrounded by blanks, but do not add blanks at the beginning or end of the string. They will only be substituted unless immediately preceded or followed by & or |.

I did it only for uppercase letters. You can easily adapt, if you must also handle lower case letters.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=84001&siteId=1