Using a regular expression to insert text in a match - regex

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

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");
}

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*")

Related

Regex pattern not matching for integers followed by strings

I want to create a regex that would start with a integer number and then it might have a colon followed by a string. For example, it should pass for:
123
123:e43e
123:444+:343
I tried using the regex as:
String timeZoneRegex = "^\\d+[:(=[a-zA-Z+-:0-9]+)]*";
This does not work; appreciate any help here.
I have to say that some regexp features depend on the regexp engine, but try with:
\d+(\:[a-zA-Z0-9\-+]+)*
I've given a look to your express, you've made some mistake, maybe the most relevat one is the use of embeded [], you should know that inside the squared brackets the behaviour of symbols intepretation is a little different. This is a very good source if you want to learn them. Cheers.

Matching Any Word Regex

I would like to remove hundreds on onmouseover events from my code. the evt all pass different variables and I want to be able to use dreamwaever to find and replace all the strings with nothing.
Here is an example
onmouseover="parent.mv_mapTipOver(evt,'Wilson');"
onmouseover="parent.mv_mapTipOver(evt,'Harris');"
onmouseover="parent.mv_mapTipOver(evt,'Walker');"
I want to run a search that will identify all of these and replace/remove them.
I have tried seemingly infinite permutations of things like:
onmouseover="parent.mv_mapTipOver(evt,'[^']');"
or
onmouseover="parent.mv_mapTipOver(evt,'[^']);"
or
onmouseover="parent.mv_mapTipOver(evt,[^']);"
or
onmouseover="parent.mv_mapTipOver(evt,'[^']+');"
And many more. I cannot find the regular expression that will work.
Any/all help would be appreciated.
Thanks a ton!
"." and "(" have special meaning in regular expressions, so you need to escape them:
onmouseover="parent\.mv_mapTipOver\(evt,'[^']+'\);"
I'm not sure if this is correct dreamweaver regex syntax, but this stuff is standard enough.
Try this one:
onmouseover="parent\.mv_mapTipOver\(evt,'.+?'\);"
And see it in action here.
When using reg expressions you have to be very careful about how you handle white space. For example the following piece of code will not get caught by most of the reg expressions mentioned so far because of the space after the comma and equals sign, despite the fact that it is most likely valid syntax in the language you are using.
onmouseover= "parent.mv_mapTipOver(evt, 'Walker');"
In order to create regexp that ignore white space you must insert /s* everywhere in the regexp that white space might occur.
The following regexp should work even if there is additional white space in your code.
onmouseover\s*=\s*"parent\.mv_mapTipOver\(\s*evt\s*,\s*'[A-Za-z]+'\s*\);"

Regex Replacing characters with zero

I have the following string 3}HFB}4AF4}1 -M}1.
I have searched for this string using the regex :
([0-9])(\})([A-Z]{3})(\})([0-9][A-Z]{2}[0-9])(\})([0-9])(\s\-)([A-Z])(\})([0-9]).
I want to replace the } with 0. The Result I am looking for is 30HFB04AF401-M01, any assistance is appriciated. The tool I am using is Regex Buddy
A possible solution
Problem solved? In JavaScript at least :-)
"3}HFB}4AF4}1 -M}1".replace(/\}/g, "0");
// "30HFB04AF401 -M01"
I'm missing the point, right?
Assuming the language is JavaScript, we can write something like
"dfghj456783}HFB}4AF4}1 -M}1fghjkl8765".replace(/(?:[\d\w\s]+)([0-9]}[A-Z]{3}}[0-9][A-Z]{2}[0-9]}[0-9] -[A-Z]}[0-9])(?:[\d\w\s]+)/g, function () {
return arguments[1].replace(/}/g, "0");
});
What's possible in other languages though may be a different story.
Try the home of RegexBuddy for details.
So you've already got an expression to find instances of the string. Now you can either use groups to replace the characters, or you can use a separate regular expression over the string you found, simply replacing the } character within group(0) (which is the entire matched part of the input). I would certainly prefer the latter.
Fred seems to have created the replacement method for you already, so I won't repeat it here.
I have managed to find a solution to the formating in the JGSoft Lanugage used by Regex Buddy, thanks to all that provided suggestions that helped me channel my thoughts in the right direction.
Solution(I am still a beginner with Regex hence the syntax might not be efficent, but it does the job!!)
Using Group Names instead of Regex assiging groups with backreference and $ syntax.
Hence to replace 0 for } in the string 3}HFB}4AF4}1 -M}1 or any similar string. I used the following search and replacement syntax
Search : (?<Gp1>([0-9]))(?:})(?<Gp2>([A-Z]){3})(?:})(?<Gp3>([0-9])([A-Z]{2})([0-9]))(?:})(?<Gp4>([0-9]))(?:\s-)(?<Gp5>([A-Z]))(?:})(?<Gp6>[0-9])
Replace : ${Gp1}0${Gp2}0${Gp3}0${Gp4}-${Gp5}0${Gp6}
Result : 30HFB04AF401-M01

Regex Pattern Matching Concatenation

Is it possible to concatenate the results of Regex Pattern Matching using only Regex syntax?
The specific instance is a program is allowing regex syntax to pull info from a file, but I would like it to pull from several portions and concatenate the results.
For instance:
Input string: 1234567890
Desired result string: 2389
Regex Pattern match: (?<=1).+(?=4)%%(?<=7).+(?=0)
Where %% represents some form of concatenation syntax. Using starting and ending with syntax is important since I know the field names but not the values of the field.
Does a keyword that functions like %% exist? Is there a more clever way to do this? Must the code be changed to allow multiple regex inputs, automatically concatenating?
Again, the pieces to be concatenated may be far apart with unknown characters in between. All that is known is the information surrounding the substrings.
2011-08-08 edit: The program is written in C#, but changing the code is a major undertaking compared to finding a regex-based solution.
Without knowing exactly what you want to match and what language you're using, it's impossible to give you an exact answer. However, the usual way to approach something like this is to use grouping.
In C#:
string pattern = #"(?<=1)(.+)(?=4).+(?<=7)(.+)(?=0)";
Match m = Regex.Match(input, pattern);
string result = m.Groups[0] + m.Groups[1];
The same approach can be applied to many other languages as well.
Edit
If you are not able to change the code, then there's no way to accomplish what you want. The reason is that in C#, the regex string itself doesn't have any power over the output. To change the result, you'd have to either change the called method of the Regex class or do some additional work afterwards. As it is, the method called most likely just returns either a Match object or a list of matching objects, neither of which will do what you want, regardless of the input regex string.

Regular expression to parse xaml binding-esque syntax

As usual, regular expressions are causing my head to hurt.
I have the following strings (as examples) which I would like to parse:
Client: {Path=ClientName}, Balance: {Path=Balance, StringFormat='{0:0.00}'}
Client: {Path=ClientName}, Balance: {Path=Balance, StringFormat='Your balance is {0:0.00}.'}
I am looking for a regular expression (or any other method) which could split the strings as follows and then get the individual key/value values of each. (The idea is to resolve each one of these to a XAML binding)
String 1: {Path=ClientName}
Path = ClientName
String 2: {Path=Balance, StringFormat='{0:0.00}'}
Path = Balance
StringFormat = {0:0.00}
At the moment I have the following regular expression to split the strings but this gets confused by the value of StringFormat due to the '}' in the value.
(?<!'){(.+?)}(?!')
Any idea how I can achieve this?
Thanks!
It gets really tiring solving this same problem over and over, but here you go:
Technically, you're doing it wrong, you should use a parser, regular expressions aren't built to deal with nested matching parenthesis, blah blah blah. We can hack this one together, though, so why not?
/(?<!'){([^'}]|'[^']+')+}(?!')/
The meat of that - {([^'}]+|'[^']+')} - looks for two things: a) anything that's not a } or a ' character ([^'}]), and b) anything that looks like a string ('[^']+'). It assumes a string is a quote, a bunch of non-quote text, and another quote. Given your examples, this should work.
It will, however, fail to match 'This is a string with \'quotes\' in it', because it isn't designed for escaped quotation marks. Adding this is simple, and involves applying the principles we just applied, so I'll leave that to you to figure out if you can. You seem to be pretty good with regular expressions, and you at least made a start on this before you asked it, so I think you can figure out how to make it match \' in a string.
EDIT: You're using 's instead of "s. Sorry about that.