【问题标题】:Java Regex to get 11 words before and after specific word recursivelyJava Regex递归获取特定单词前后的11个单词
【发布时间】:2020-01-10 23:04:25
【问题描述】:

我试图在字符串中的特定单词之前和之后获取 11 个单词。

例如:

and WINSOCK 2.0 in Visual Studio 2012/2013, compiled as Release for use on 64-bit and 32-bit Windows Servers. Client application discovers and validates qualifying Windows Server product

现在这里的挑战是识别像 32 这样的单词,它用连字符连接到单词位。如果我将此单词更改为 32+bit 而不是 32-bit... 正则表达式会识别并在句子前后获得 11 个单词。

我的正则表达式看起来像

Pattern pattern = Pattern.compile("(?<!-)\\b(?<!&)(" + "\\b" + word + "\\b" + ")(?!&)\\b(?!-)(?:[^a-zA-Z'-]+[a-zA-Z'-]+){0,11}");

我寻求任何帮助。

附注* 我无法识别带有连字符的单词

@Solution感谢@Wiktor

\\b(?<!&)\\b" + word + "\\b(?!&)(?:[^a-zA-Z']+[a-zA-Z'-]+){0,11}

谢谢。

【问题讨论】:

  • 那么你想让32位被识别为1个字还是2个字?
  • 我只想识别单词 32.. 模式应该匹配.. 我不需要完整的单词 {32-bit}。谢谢
  • 所以32-bit 应该被识别为32 bit?
  • 那为什么还要包含连字符呢? "\\b(?&lt;!&amp;)\\b" + word + "\\b(?!&amp;)(?:[^a-zA-Z']+[a-zA-Z'-]+){0,11}" 应该可以工作
  • @Nick 我需要从任何字符串中获取单词 32 的上下文并突出显示 .. 现在在我的情况下 .. 因为字符串中存在 32 它应该匹配并且应用程序级别它将突出显示(仅突出显示第 32 个单词)..

标签: java regex


【解决方案1】:

您可以从正则表达式中“取出”连字符:

"\\b(?<!&)" + word + "\\b(?!&)(?:[^a-zA-Z']+[a-zA-Z'-]+){0,11}"

或者,如果单词可能以特殊字符开头/结尾:

"(?<![&\\w])" + Pattern.quote(word) + "(?![&\\w])(?:[^a-zA-Z']+[a-zA-Z'-]+){0,11}"

regex demo

详情

  • \b(?&lt;!&amp;) - 前面没有&amp; 的单词边界
  • word - 一个可变词(请注意,如果 word 可能以特殊字符开头/结尾,您可能需要使用 Pattern.quote(word) 对其进行转义,或者甚至将 "\\b(?&lt;!&amp;)" + word + "\\b(?!&amp;)" 替换为 "(?&lt;![&amp;\\w])" + word + "(?![&amp;\\w])"
  • \b(?!&amp;) - 不跟&amp; 的字边界
  • (?:[^a-zA-Z']+[a-zA-Z'-]+){0,11} - 0 个或多个序列:
    • [^a-zA-Z']+ - 除 ASCII 字母或 ' 以外的 1+ 个字符
    • [a-zA-Z'-]+ - 1+ ASCII 字母或'

【讨论】:

  • 我添加了一个正则表达式的变体,如果您的 word 可能以特殊的正则表达式元字符(如 ([+ 等)开始/结束,这将很有用
  • @WiktorStribiżew 您的解释对我有很大帮助。我希望它对像我这样完全不了解 Regex 的人有所帮助。
【解决方案2】:

如果你不必使用正则表达式,那么:

String message = "and WINSOCK 2.0 in Visual Studio 2012/2013, compiled as Release for use on 64-bit and 32-bit Windows Servers. Client application discovers and validates qualifying Windows Server product";


String target = "32-bit";
int index = message.indexOf("32-bit");
int lenght = target.length();

String before = message.substring(index -11, index);
String after = message.substring(index + lenght , index + lenght + 11);

Log.i("tag", "index: " + index);
Log.i("tag", "before: " + before);
Log.i("tag", "after: " + after);

【讨论】:

    猜你喜欢
    • 2017-11-07
    • 1970-01-01
    • 1970-01-01
    • 2018-01-15
    • 2023-01-27
    • 2017-10-02
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    相关资源
    最近更新 更多