【问题标题】:Get substring with n chars before and after the found sequence在找到的序列之前和之后获取具有 n 个字符的子字符串
【发布时间】:2011-06-11 13:09:40
【问题描述】:

我有一个名为 text 的大型字符串变量。我希望能够检查text 是否包含指定的searchString(例如“test”)并在匹配前后返回所有带有windowSize 字符的子字符串。

例子:

String windowSize = 5;
String text = "this is only a simple test. lorem impsum testing everything.";
String searchString = "test";

因此我想要以下输出:

mple test. lor
ssum testing e

另外,如果能够有不同类型的输出,那就太好了:

仅在之前:

mple 
ssum 

仅在:

. lor
ing e

解决方案

感谢 Peter Lawrey 和 SubmittedDenied 我得到了答案:

String windowSize = 5;
String text = "this is only a simple test. lorem impsum testing everything.";
String searchString = "test";

int i = -1;
while((i = text.indexOf(searchString, i+1)) > -1) {
    System.out.println(text.substring(Math.max(0, i - windowSize), Math.min(i + searchString.length() + windowSize, text.length())));
}

【问题讨论】:

  • 你必须使用正则表达式吗? String.indexOf() 会更简单更快。
  • 你是对的,没有想到更简单的解决方案。

标签: java regex window substring


【解决方案1】:

您可以使用indexOf(string) 方法找到子字符串的位置,如果没有这样的子字符串,这也会返回-1

你想做这样的事情:

String windowSize = 5;
String text = "this is only a simple test. lorem impsum testing everything.";
String searchString = "test";
int i = -1;
while((i = text.indexOf(test, i + 1)) > -1)
{
    System.out.println(text.substring(i - windowSize, i + searchString.length() + windowSize));
}

您可能需要捕获错误,例如 test 的第一次出现少于字符串中的 windowSize 字符。

【讨论】:

  • 这会导致无限循环,因为text.indexOf(test) 总是返回相同的结果。
  • 啊,当然,我会编辑答案以使用indexOf(string, startindex) - 我知道我忘记了什么!
  • 你需要text.indexOf(text, i+1),当比赛接近开始和/或结束时,你还需要Math.max(0, i - windowsSize), Math.min(i + searchString.length() + windowSize, text.length())
  • @SubmittedDenied,它必须是i+1,否则你有另一个无限循环。 ;)
  • 感谢你们俩。我用得到的解决方案更新了我的问题。
【解决方案2】:
int windowSize = 5;
String text = "this is only a simple test. lorem impsum testing everything.";
String searchString = "test"; 
Pattern pattern = new Pattern ("(.{" + windowSize + "})" + Pattern.Quote (searchString) + "(.{" + windowSize + "})");

如果您只想获得之前或之后,请使用第一个或第二个匹配组。 (圆括号标记了之前和之后的区域。

【讨论】:

  • 如果你想匹配到windowsize,那么使用这个表达式:new Pattern ("(.{," + windowSize + "})" + Pattern.Quote (searchString) + "( .{," + windowSize + "})"); // 窗口大小前的逗号
  • 这只会匹配一个,但您可以添加 +* 以轻松修复它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-06
  • 1970-01-01
  • 1970-01-01
  • 2022-11-10
  • 2022-01-09
  • 1970-01-01
  • 2012-02-10
相关资源
最近更新 更多