views:

90

answers:

5

Hello. I've got some text where some words are "real" words, and others are masks that will be replaced with some text and that are surrounded with, say, "%". Here's the example:

Hello dear %Name%! You're %Age% y.o.

What regular expression should I use to get "real" words, without using lookbehind, because they don't exist in JavaScript?

UPD: I want to get words "Hello", "dear", "you're", "y.o.".

+1  A: 

If I've understood your question correctly this might work.

I would go about it the other way around, instead of finding the real words I would remove the "fake-words."

s = "Hello dear %Name%! You're %Age% y.o."
realWords = s.replace(/%.*?%/g, "").split(/ +/)
adamse
+1  A: 

You could use split to get the words and filter the words afterwards:

var str = "Hello dear %Name%! You're %Age% y.o.", words;
words = str.split(/\s+/).filter(function(val) {
    return !/%[^%]*%/.test(val);
});
Gumbo
A: 

To do a search and replace with regexes, use the string's replace() method:

myString.replace(/replaceme/g, "replacement")

Using the /g modifier makes sure that all occurrences of "replaceme" are replaced. The second parameter is an normal string with the replacement text.

Todd Moses
A: 

You can match the %Something% matches using %[^%]*?%, but how are you storing all of the individual mask values like Name and Age?

Ben
The text is provided by a user and is a message with some masks. The message is in Russian, so what I finally want to achieve is to transliterate all the words, except for the words that are masks. Transliterated message is then transfered to server, parsed there, and masks are replaced with the real values.
HiveHicks
A: 

Use regular expression in Javascript and split the string based on matching regular expression.

//javascript
var s = "Hello dear %Name%! You're %Age% y.o.";
words = s.split(/%[^%]*?%/i);

//To get all the words
for (var i = 0; i < words.length; i++) {

}
The Elite Gentleman