Advertisement
JoshDreamland

Revamped line match finder

Sep 28th, 2014
211
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.08 KB | None | 0 0
  1. // Copyright (C) 2014 Josh Ventura
  2. // Code is part of LateralGM <lateralgm.org> and is released under the terms of
  3. // the GNU General Public License as published by the Free Software Foundation;
  4. // version 3 of the license, or any later version.
  5.  
  6. private static final Pattern newline = Pattern.compile("\r\n|\r|\n");
  7. public static LineMatch[] getMatchingLines(String code, Pattern content) {
  8.   List<LineMatch> res = new ArrayList<>();
  9.   Matcher m = content.matcher(code), nl = newline.matcher(code);
  10.   int lineNum = 1, lineAt = 0, lastEnd = -1;
  11.   LineMatch lastMatch = null;
  12.   while (m.find()) {
  13.     nl.region(lineAt, m.start());
  14.     int firstSkippedLineAt = lineAt;
  15.     if (nl.find()) {
  16.       firstSkippedLineAt = nl.start();
  17.       lineAt = nl.end();
  18.       ++lineNum;
  19.       while (nl.find()) {
  20.         ++lineNum;
  21.         lineAt = nl.end();
  22.       }
  23.     }
  24.     if (lastMatch != null) {
  25.       // We have to add the rest of the line to the old match, either way.
  26.       // And if we're matching on the same line, we add that match, too.
  27.       if (lineNum == lastMatch.lineNum) {
  28.         lastMatch.matchedText.add(new MatchBlock(code.substring(lastEnd, m.start()), false));
  29.         lastMatch.matchedText.add(new MatchBlock(code.substring(m.start(), m.end()), true));
  30.       } else {
  31.         lastMatch.matchedText.add(
  32.             new MatchBlock(code.substring(lastEnd, firstSkippedLineAt), false));
  33.       }
  34.     }
  35.     if (lastMatch == null || lineNum != lastMatch.lineNum) {
  36.       lastMatch = new LineMatch();
  37.       lastMatch.lineNum = lineNum;
  38.       if (m.start() > lineAt) {
  39.         lastMatch.matchedText.add(new MatchBlock(code.substring(lineAt, m.start()), false));
  40.       }
  41.       lastMatch.matchedText.add(new MatchBlock(code.substring(m.start(), m.end()), false));
  42.       res.add(lastMatch);
  43.     }
  44.     lastEnd = m.end();
  45.   }
  46.   if (lastMatch != null) {
  47.     nl.region(lastEnd, code.length());
  48.     int indTo = (nl.find())? nl.start() : code.length();
  49.     lastMatch.matchedText.add(new MatchBlock(code.substring(lastEnd, indTo), false));
  50.   }
  51.   return res.toArray(new LineMatch[] {});
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement