user2190690
user2190690

Reputation: 2034

Using a regular expression to insert text in a match

Regular Expressions are incredible. I'm in my regex infancy so help solving the following would be greatly appreciated.

I have to search through a string to match for a P character that's not surrounded by operators, power or negative signs. I then have to insert a multiplication sign. Case examples are:

33+16*55P would become 33+16*55*P
2P would become 2*P
P( 33*sin(45) ) would become P*(33*sin(45))

I have written some regex that I think handles this although I don't know how using regex I can insert a character:

The reg is I've written is:

[^\^\+\-\/\*]?P+[^\^\+\-\/\*]

The language where the RegEx will be used is ActionScript 3.

A live example of the regex can be seen at:

http://www.regexr.com/39pkv

I would be massively grateful if someone could show me how I insert a multiplication sign in middle of the match ie P2, becomes P*2, 22.5P becomes 22.5P

ActionScript 3 has search, match and replace functions that all utilise regular expressions. I'm unsure how I'd use string.replace( expression, replaceText ) in this context.

Many thanks in advance

Upvotes: 0

Views: 5994

Answers (2)

tmoore82
tmoore82

Reputation: 1875

Welcome to the wonder (and inevitable frustration that will lead to tearing your hair out) that is regular expressions. You should probably read over the documentation on using regular expressions in ActionScript, as well as this similar question.

You'll need to combine RegExp.test() with the String.replace() function. I don't know ActionScript, so I don't know if it will work as is, but based on the documentation linked above, the below should be a good start for testing and getting an idea of what the form of your solution might look like. I think @Vall3y is right. To get the replace right, you'd want to first check for anything leading up to a P, then for anything after a P. So two functions is probably easier to get right without getting too fancy with the Regex:

   private function multiplyBeforeP(str:String):String {
      var pattern:RegExp = new RegExp("([^\^\+\-\/\*]?)P", "i");
      return str.replace(pattern, "$1*P");
  }

   private function multiplyAfterP(str:String):String {
      var pattern:RegExp = new RegExp("P([^\^\+\-\/\*])", "i");
      return str.replace(pattern, "P*$1");
  }

Upvotes: 2

Vall3y
Vall3y

Reputation: 1181

Regex is used to find patterns in strings. It cannot be used to manipulate them. You will need to use action script for that.

Many programming languages have a string.replace method that accepts a regex pattern. Since you have two cases (inserting after and before the P), a simple solution would be to split your regex into two ([^\^\+\-\/\*]?P+ and P+[^\^\+\-\/\*] for example, this might need adjustment), and switch each pattern with the matching string ("*P" and "P*")

Upvotes: 2

Related Questions