Log in

View Full Version : Getting Regular Expression To Repeat



SaishuHane
06-21-2014, 07:52 PM
I'm trying to write a regex that replaces all spaces with hyphens, but only if those spaces are within an h2. I want it to repeat as many times as I need to through a document, but it only ever hits the first.


(^[<h2>]+)?((\w*)*)((\s*)*)

Replacing with


$1$2-

This is as close as I've been able to get it to produce so far


<h2>dota dota dota dota dota</h2>

To


<h2>dota-dota-dota-dota-dota-</h2>

I'm not even 100% sure why it puts that hyphen just before the last h2, but I'm much more concerned about it repeating.

jscheuer1
06-21-2014, 11:45 PM
What language are you using? Javascript, PHP, something else?

And can you show the whole script?

How about:


<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<h2>dota dota dota dota dota</h2>
<h2>bob bob bob bob bob</h2>
<script type="text/javascript">
var h2s = document.getElementsByTagName('h2'), h2 = h2s.length;
while(--h2 > -1){
h2s[h2].innerHTML = h2s[h2].innerHTML.replace(/\s/gm, '-');
}
</script>
</body>
</html>

james438
06-23-2014, 02:16 AM
Just for fun here's an example using php:


<?php
$string = " <h2>dota dota dota dota dota </h2> ";
$string = preg_replace('/ (?=((?!<\/?h2\b|>).)*<\/h2)/','-',$string);
echo "$string";
?>

SaishuHane
06-23-2014, 04:17 PM
Sorry about that, I should have mentioned that I've been using Dreamweavers find and replace with "Use Regular Expression" turned on.

jscheuer1
06-23-2014, 04:50 PM
Sorry, I'm not aware of how DW utilizes RE. I can tell you that using ^ (if it means in DW what it means in all RE's) is not the best choice, because it means the beginning of a line. If the h2's you are targeting are not always at the beginning of a line, they will be skipped. You should be able to simply skip using ^ to correct that. Now, is there a switch in DW to force global over first instance? If so that should be applied. But simply dropping the ^ might be all you need to solve that problem (global is the default in my word processor that takes RE as an option).

SaishuHane
06-23-2014, 06:45 PM
Maybe for Dreamweaver, the answer is that there isn't one for this specific problem. I tried taking ^ out and it spit this out:


<h2>asldk-adksfj-asdlkfj-asdkfj-kdsaf-kjk-<-/h2>

Even less sure why it put a hyphen just before the slash. Unfortunately, the only checkbox available concerning regular expressions is "use regular expression".

jscheuer1
06-23-2014, 08:16 PM
Read the online help then. I meant switches like g (global) or m (multiline). In javascript and most other languages you put a comma at the end of the expression and follow that with one or more switches:


(^[<h2>]+)?((\w*)*)((\s*)*),gm

or:


/(^[<h2>]+)?((\w*)*)((\s*)*)/,gm

That may or may not work with DW. I'm sure it has documentation somewhere:

http://lmgtfy.com/?q=dreamweaver+regular+expression+usage