0

guys help me please with it. I don't know how to operate with regex, I read a lot about this, but anyway, I don't understand how it works.

This is my problem: I have code like this:

var str = "<strong>What do you think</strong> if we could just buy this <strong>Robot</strong>"; 
str = str.match(/[<strong>][a-z\s]+[<\/strong>]/gi);

And after code is done, I get something like this: >What do you think<,>Robot<

But I waited for this: What do you think, Robot.

What's wrong? It drives me crazy.

UPDATE: Thanks to all of you!!! Now, solution is found

Jerome
  • 67
  • 5

3 Answers3

1

try this regex expression [updated]

(<strong>(.*?)</strong>)*
rs.
  • 26,707
  • 12
  • 68
  • 90
  • 1
    Thanks, it works, but anyway, I've got : Robot instead: Robot. Or I can't rid of these tags? – Jerome Mar 23 '12 at 16:09
  • Unfortunately, it doesn't work. I've constantly get the same thing, plus now I've get a lot of commas (from the text that I have) – Jerome Mar 23 '12 at 16:33
0

This is how its done in most (modern) regex dialects

.*?(?<=<strong>)(.*?)(?=</strong>).*?|.*

replace with

$1

Unfortunately, Javascript does not support lookbehind. If you are up for it you can read http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript and give it a go. Pity js doesn't support such a powerful technique

buckley
  • 13,690
  • 3
  • 53
  • 61
  • That's not quite what he wanted. He just wants the text between the `` tags. – gen_Eric Mar 23 '12 at 16:18
  • Yes, Rocket is right, I just want the text between that tags. And when I use replace - it doesn't work, I don't know why, before I post my question here, I've alredy tryied to use replace for result, but something wrong with it. Just because, I don't get the result, after I use "replace" – Jerome Mar 23 '12 at 16:36
0

If you don't feel like fussing with RegExp.exec(), use this:

var matches = str.match(/<strong>.*?<\/strong>/gi);
var result = [];
for (var i = 0; i < matches.length; ++i)
    result.push(matches[i].match(/<strong>(.*)<\/strong>/i)[1]);
Alexander Pavlov
  • 31,598
  • 5
  • 67
  • 93
  • Yeah!!! Finally... Wow. It works. I'm really happy now. Thanks a lot. Could you explain this logic step by step, please? I'll be appreciate it. – Jerome Mar 23 '12 at 16:43
  • Sure. The first, non-greedy, matcher extracts all the `..` tags (the `?` helps avoid greedy matching: `.......` - this string matches `/.*<\/strong>/` that was suggested in another answer. The `g` (global) flag gives you all matches in an array (an example [here](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/match#Example:_Using_global_and_ignore_case_flags_with_match)). Now you just have to extract the `` tag contents in a loop using greedy matching, like other answers suggested. – Alexander Pavlov Mar 23 '12 at 16:51
  • It's awesome. With your help I made a little step in Javascript's regex. – Jerome Mar 23 '12 at 17:22