joeellis
joeellis

Reputation: 2785

Javascript RegEx match problem

I have a sentence structure along the lines of

[word1]{word2} is going to the [word3]{word4}

I'm trying to use a javascript regex to match the words for replacement later. To do this, I'm working towards getting the following multi-dimensional array:

[["word1", "word2"],["word3","word4"]]

I'm currently using this regex for the job:

\[(.*?)\]\{(.*?)\}

However, it comes up with results like:

["[word1]{word2}", "word1", "word2"]

or worse. I don't really understand why because this regex seems to work in Ruby just fine, and I'm not really much of a regex expert in general to understand what's going on. I'm just curious if there are any javascript rege expert's out there to whom this answer is very clear and can guide me along with what's going on here. I appreciate any help!

Edit:

This is the code I'm using just to test the matching:

function convertText(stringText) {
     var regex = /\[(.*?)\]\{(.*?)\}/;
    console.log(stringText.match(regex));
}

Upvotes: 1

Views: 1081

Answers (2)

Mark Byers
Mark Byers

Reputation: 837996

I assume you are using the exec method of the regular expression.

What you are doing is almost correct. exec returns an array where the first element is the entire match and the remaining elements are the groups. You want only the elements at indexes 1 and 2. Try something like this, but of course store the results into an array instead of using an alert:

var string = '[word1]{word2} is going to the [word3]{word4}';
var pattern = /\[(.*?)\]\{(.*?)\}/g;
var m;
while(m = pattern.exec(string)) {
    alert(m[1] + ',' + m[2]);
} 

This displays two alerts:

  • word1,word2
  • word3,word4

Upvotes: 1

Robusto
Robusto

Reputation: 31883

What you're seeing is Japanese hiragana. Make sure your input is in English maybe?

Edited to say: Upon further review, it looks like a dictionary entry in Japanese. The 私 is kanji and the わたし is hiragana, a phonetic pronunciation of the kanji. FWIW, the word is "Watashi" which is one of the words for "I" (oneself) in Japanese.

Upvotes: 0

Related Questions