提取匹配的文本及其相邻上下文n个下游n个字下游(从左起第n个和从右起第n个) [英] Extract matched text and its neighboring context n words upstream n words downstream (nth occurrence from left and nth occurrence from right)

查看:122
本文介绍了提取匹配的文本及其相邻上下文n个下游n个字下游(从左起第n个和从右起第n个)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在自动完成下拉菜单中很适合的文字。这需要比最初出现的策略更多的策略。使用隐藏文本或淡出选项不能很好地工作,因为匹配的文本字符串通常在其上下文的可见框架之外。省略号方法目前比我需要的有点重。 显示更多效果很好,但不是在下拉框的上下文中;我不想让用户担心除了选择选项之外的任何东西。我只想要一个或两个上下文围绕匹配的令牌。有一些相关的答案,但没有什么完全解决n和n从左边的需要。

I need text that fits nicely in an autocomplete dropdown. This required more strategy than it would initially appear. Using hidden text or fadeout option didn't work well because the matched text string was often outside of the visible frame of its context. The ellipsis approach currently is a bit heavier weight than I need. "Show more" works well, but not in the context of the dropdown box; I don't want the user to worry about anything except selection of the option. I just want a line or two of context centred around the matched token. There are some related answers, but nothing that quite addresses the need for both n from the right and n from the left.

var haystack = "r4 r3 r2 r1 needle r1 r2 r3";
var needle = "needle";
var delim = " ";
var numWords = 5;
var trimmedText = trimToNeighboringText(haystack, needle, numWords, delim);

console.log("With " + numWords + " neighboring words: \"" + trimmedText + "\"");


推荐答案

正则表达式可以简化很多!

这里是我的解决方案:

Regex can simplify this a lot!
Here is my solution:

var haystack = "L5 L4 L3 L2 L1 needle R1 R2 R3 R4 R5 R6",
    needle = "needle",
    numWords = 3;

var result = haystack.match("(?:\\s?(?:[\\w]+)\\s?){"+numWords+"}"+needle+"(?:\\s?(?:[\\w]+)\\s?){"+numWords+"}");

console.log("With " + numWords + " neighboring words: \"" + result[0] + "\"");




具有3个邻近字词:L3 L2 L1 needle R1 R2 R3

这篇关于提取匹配的文本及其相邻上下文n个下游n个字下游(从左起第n个和从右起第n个)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆