0

I need to modify a string using REGEX in js that too in two ways

1) Operators(AND|OR) in string must have a leading and trailing whitespace ie if say string is

(C1 AND C2 ORC3) AND (C4OR C5) then must be modified to (C1 AND C2 OR C3) AND (C4 OR C5)

2) parenthesis must not have whitespace in between them and also with conditions(Cn) ie

( ( C1 AND C2 OR C3) ) AND ( C4 OR C5) then it must be modified to ((C1 AND C2 OR C3)) AND (C4 OR C5)

6
  • operators used are only AND|OR .. nd nothing else also parenthesis are also to be only () .. no square brackets or anythin else will be there in string Commented Apr 10, 2013 at 6:03
  • 2
    What's the issue you are having? Have you tried anything? Commented Apr 10, 2013 at 6:06
  • Is there a problem if AND/OR are separated by two spaces rather than just one? Commented Apr 10, 2013 at 6:09
  • 1
    i need a simple regex to staisfy the condition .. @RohitJain is ques not clear enough .. Commented Apr 10, 2013 at 6:09
  • @ExplosionPills if that is the case i can trim down the multiple whitespaces with single whitespace later on.. ;) Commented Apr 10, 2013 at 6:10

4 Answers 4

3

You can do this :

var str = .replace(/(AND|OR)(\w)/g, "$1 $2")
          .replace(/(\w)(AND|OR)/g, "$1 $2")
          .replace(/\(\s/g, "(")
          .replace(/\s\)/g, ")");

It changes

"( ( C1 AND C2 ORC3 ) ) AND ( C4 ORC5)"

to

"((C1 AND C2 OR C3)) AND (C4 OR C5)"

It could be made shorter but would lose readability.

Sign up to request clarification or add additional context in comments.

Comments

2

I wont write a single code. But the idea will give you the solution with a little php knowledge.

  • replace all AND and OR with <space>AND<space> and <space>OR<space> Look carefully the second version have white spaces around them.

  • replace all double white space with single one. Loop through this rule untill there is no double white space.

  • replace (<space> with ( and <space>) with ). Again looks carefully

<space> means white space here.

Comments

1
.replace(/\s*([()])\s*/g, "$1")
.replace(/AND|OR/g, " $& ")
.replace(/\s+/g, ' ');

This works properly on your last test string. It should account for more than one space separating parentheses and even trims extra space.

Comments

0
function attempt(str){
   return str.replace(/\s/g,"").replace(/(AND|OR)/g," $1 ");
}
function test(){
    var str = '( ( C1ANDC2 OR C3)          ) AND     ( C4  ORC5)',
        expected = '((C1 AND C2 OR C3)) AND (C4 OR C5)';
    return attempt(str) ===  expected;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.