Tutorial :How to process this string via regular expression



Question:

my string style like this

expression1/field1+expression2*expression3+expression4/field2*expression5*expression6/field3  

a real style mybe like this:

computer/(100)+web*mail+explorer/(200)*bbs*solution/(300)  

"+" and "*" represent operator "computer","web"...represent expression (100),(200) represent field num . field num may not exist.

I want process the string to this:

<computer>/(100)+web*<mail>+explorer/(200)*bbs*<solution>/(300)  

rules like this

if expression length is more than 3 and its field is not (200), then add brackets to it.


Solution:1

My recommendation is to mix regex with other language features. The complication arises from the fact that field appears before expressions, and lookbehind is usually more limited than lookforward.

In pseudo-Java-code, I recommend doing something like this:

String[] parts = input.split("/");    for (int i = 0; i < parts.length; i++) {    if (!parts[i].startsWith("(200)"))      parts[i] = parts[i].replaceAll("(?=[a-z]{4})([a-z]+)", "<$1>");  }    String output = parts.join("/");  


Solution:2

I would not use just regular expression.

You say "if expression length is more than 3 and its field is not (200), then add brackets to it"

I think a normal conditional statement is the best and clearest solutoion for this.

I think regular expressions are sometimes overused. Regexes are hard to read, and when a couple of conditional statements can do the same but more clearly, then I'd say the code quality is higher.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »