views:

46

answers:

2

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.

A: 

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.

Niels Bom
I disagree that regex is overused/hard to read. The reason why it isn't suitable here is because `field` appears before the `expression` to be bracketed, and lookbehind is usually more limited than lookforward. If `field` appears at the end of `expression`s, this is actually quite trivial and the regex is very readable.
polygenelubricants
A: 

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("/");
polygenelubricants
pretty good. i have used it
iiduce