Yooz
Yooz

Reputation: 2518

Javascript - Regular expressions Not consistent match

I am getting crazy with this problem, I try to extract "Latin" sentences from the following string (shorter than the original) :

My Name is Yoann

ホームインサイト最新のインサイト運用チームからの最新のマーケ
ットアップデート、運用アップデートマーケットアップデート市場環境情報に関す
るレポート投資アップデート投資環境情報レポート及び出版物運用戦略運用戦略
ファーストステート・スチュワートアジア・パシフィック、グローバル・エマージング・マーケット、ワールドワイド株式

Hello World

Here is the regular expression :

...
//text=My Name is Yoann...
pattern = new RegExp("([A-Za-z]+[\s]?[A-Za-z])+", "g");
results= text.match(pattern);

When I run that, I get :

//results[0]="My"
//results[1]="Name"
//results[2]="is"
//results[3]="Yoann"
//...

The words are splitted on "space". When I try on the http://regexlib.com (JS client engine) tester or http://regexpal.com, the results are :

//results[0]="My Name is Yoann"
//results[1]="Hello World"

So I don't understand what i do wrong in my code but I don't get the same results.

Thanks for your help.

Yoann

Upvotes: 0

Views: 206

Answers (1)

georg
georg

Reputation: 215039

> "foo bar".match(new RegExp("[a-z]\s[a-z]"))
null
> "foo bar".match(new RegExp("[a-z]\\s[a-z]"))
["o b"]

When using the RegExp constructor, double your slashes. Better yet, use regex literals, e.g.

/[A-Z][A-Z\s]*[A-Z]|[A-Z]/gi

http://jsfiddle.net/4PdJh/1

Upvotes: 4

Related Questions