2

私はこのような文字列を持っています: This is my text

結果として取得しisたいような文字列を検索するとき、取得したい結果を検索するときは、This is myThisThis istextmy text

したがって、私は常に文字列を検索し、検索された文字列+存在する場合は前後の単語を取得しようとします。

mystring.match('search')文字列を検索してインデックスを取得できることはわかっていますが、どうすればさらに先に進むことができsplitますか?

多分あなたの誰かが考えを持っています。

助けのためのThx

ルーヴェン

4

5 に答える 5

3

検索する単語とその単語を検索する文字列の両方を渡すことができる機能的なアプローチを使用する次のアプローチをお勧めします。

function findWordAndNeighbours(needle, haystack) {
    if (!needle || !haystack) {
        return false;
    }
    else {
        var re = new RegExp('(\\S+[\\b\\s]' + needle + '[\\b\\s]\\S+)', 'i'),
            foundWords = haystack.match(re)[0].split(/\s+/),
            foundFragment = foundWords.join(' ');
        return foundFragment;
    }
}

var sentenceFragment = findWordAndNeighbours('test', 'This is a Test of a matching thing.');

console.log(sentenceFragment);

JS フィドルのデモ

上記を更新して、いくつかのエラーキャッチを含めるように編集し、基本的に、それらの一致を処理する前にいくつかの正規表現の一致があることを確認します

function findWordAndNeighbours(needle, haystack) {
    if (!needle || !haystack) {
        return false;
    }
    else {
        var re = new RegExp('(\\S+[\\b\\s]' + needle + '[\\b\\s]\\S+)', 'i'),
            matches = haystack.match(re);
        if (matches) {
            // this is for if you wanted the individual words (as an array)
            var foundWords = haystack.match(re)[0].split(/\s+/),
                // this is to return the found sentence-fragment:
                foundFragment = foundWords.join(' ');
            return foundFragment;
        }
        else {
            /* this just follows the indexOf() pattern of, if you'd rather
               'return false' instead, that's entirely your call. */
            return -1;
        }
    }
}

var sentenceFragment = findWordAndNeighbours('test', 'This is a Test of a matching thing.');

console.log(sentenceFragment);

JS フィドルのデモ

コメントでOPによって特定された問題を修正するために編集されました(以下):

ただし、This または Thing を検索するとこれは機能しないため、最初または最後の単語を

?オペランド/特殊文字 (前の文字/グループを 0 回または 1 回一致させることを意味する) を使用すると、指定された文字列の最初と最後の単語を検索する際の問題が修正されるようです。

function findWordAndNeighbours(needle, haystack) {
    if (!needle || !haystack) {
        return false;
    }
    else {
        var re = new RegExp('((\\S+[\\b\\s]?)' + needle + '([\\b\\s]?\\S+))', 'i'),
            matches = haystack.match(re);
        console.log(matches);
        if (matches) {
            var foundWords = haystack.match(re)[0].split(/\s+/),
                foundFragment = foundWords.join(' ');
            return foundFragment;
        }
        else {
            return -1;
        }
    }
}

var sentenceFragment = findWordAndNeighbours('es', 'This is a Test of a matching thing.');

console.log(sentenceFragment);

ただし、特定の単語から部分文字列を検索する適切な方法を見つけることができませんでした。たとえば、es(例のように from test)。関数は完全な単語を返します (この場合はtest)。その動作を簡単に修正したい場合は、簡単にif (needle == matches[0]) {/* do something */}チェックを追加して、最適と思われる動作を変更できます。しかし、それを処理する最善の方法が何であるかは完全にはわかりません。

参考文献:

于 2012-09-30T14:10:00.210 に答える
1
'asd d This is my text a'.match(/\s(\w*\sis\s\w*)\s/)[1] //=> "This is my"
于 2012-09-30T13:39:46.920 に答える
1

これを試して

これが実際の例です

コードはjavascriptです

var str = "This is my text";

var strArr = str.split(" ");

var seacrhWord = "is";

for (i=0; i<strArr.length; i++)
   {
      if ( strArr[i] == seacrhWord)
      {
          var result = "";
          if (strArr[i-1] != null)
             result += strArr[i-1]

          result += " " + strArr[i];

          if (strArr[i+1] != null)
             result += " " + strArr[i+1];

          alert(result);
      }
  }
于 2012-09-30T13:44:22.820 に答える
1

さらに別の解決策:

var input = 'Text? This is my simple text string where I use word TEXT a few times. Is it finding my text?'
var text = 'text';

input = input.toString();
text = text.toString().replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');

var preLength = 7;

var search = function () {
    if (position !== -1) {
        var sliceStart = (position - preLength) >= 0 ? position - preLength : 0;
        var sliceEnd = position + text.length + preLength;

        var matchedText = input.slice(sliceStart, sliceEnd).trim();

        var preText = ((position - preLength) >= 0) && !result.length ? '...' : '';
        var postText = input.slice(sliceEnd).trim().length > 0 ? '...' : '';

        result = result + preText + matchedText + postText;

        input = input.slice(sliceEnd);
        lowercaseInput = lowercaseInput.slice(sliceEnd);

        position = lowercaseInput.search(lowercaseText);
    }
}

var lowercaseInput = input.toLowerCase();
var lowercaseText = text.toLowerCase();

var result = '';
var position = lowercaseInput.search(lowercaseText);

while (position !== -1) {
    search();
}

console.log(result);

これは、検索されたテキストを検索し、すべての一致を含む結果を返します。

http://jsfiddle.net/bqwn1whq/

于 2014-10-23T12:17:51.113 に答える
0

私の意見では、「this i」などの場合、正規表現を使用できます。3 または 4 の場合は ^this ? で開始します。しかし、注意しないと、この検索は不健康です。スペースと一致しない用語は、この i* に一致させるのが難しい問題を引き起こす可能性があります。for substring match match(/y​​oursearchterm/[A-Za-z0-9_-]*/i) 一致しない場合、yoursearchterm.substring(0,yoursearchterm.length-1) のような yoursearchterm の部分文字列を for ループで使用してみてください類似度 -1 から -i 、

sql の全文検索または同様の式。より良い結果を得るには、sqlの正規表現が役立つ場合がありますが、どちらも{likeとregexはあまり高速ではありません}レーベンシュタイン経由。php http://php.net/manual/en/function.levenshtein.php では、部分文字列または長い文の場合、データをスペースで分割 {または分解} する方法を使用できます。つまり、ここに私がいて、あなたのデータが分割されています 3 ここに私は両方とも lev を適用できます。

于 2012-09-30T13:47:24.427 に答える