2

「。」を置き換えたい [ドット]のようなトークンに入力の下から出力の下へ

入力

これは質問のテストです。stackoverflow.comで学ぶのに最適な場所。プログラミング。テストwww.wikipedia.com

出力

これは質問のテストです。stackoverflow[dot]comで学ぶのに最適な場所です。プログラミング。テストwww[dot]wikipedia [dot] com

問題

  1. 以下のようなものを使用するのに最適だと思うtest.forような、良い正規表現を使用できない可能性があります/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}/gi
  2. 多分私は解決策を見つけました。

found = string.match(/([a-zA-Z0-9]+\.(com|co\.cc)|more\.domains)/gi);

これはうまく機能します。元の文字列に結合/置換するのに問題があります。javascriptを使用して配列内の正規表現を使用して配列内の要素をフィルタリングする方法などの回避策はありますか?

この問題にどのように取り組みますか?ところで、nodejsの他の言語を使用することは許容されます。

ありがとう

4

2 に答える 2

3

これはwww.example.com正しく処理されます:

tld = ["com", "org", "edu", "net"] // feel free to add more

var input = "this is a test.for a question. at www.stackoverflow.com " 
    + "the best place to learn. "
    + "programming.test wikipedia.com and windows.microsoft.edu";


re = new RegExp('\\S+\\.(' + tld.join('|') + ')\\b', 'g')

var dotted = input.replace(re, function($0) {
    return $0.replace(/\./g, "[dot]");
});

// this is a test.for a question. at www[dot]stackoverflow[dot]com the best place to learn. 
// programming.test wikipedia[dot]com and windows[dot]microsoft[dot]edu
于 2012-10-31T18:23:30.353 に答える
1
var input = "this is a test.for a question. at stackoverflow.com the best place to learn. programming. test wikipedia.com";
var dotted = input.replace(/(\S+)\.(com|org|edu|net)\b/gi, '$1[dot]$2');
// "this is a test.for a question. at stackoverflow[dot]com the best place to learn. programming. test wikipedia[dot]com"
于 2012-10-31T17:40:50.253 に答える