From bf69d6c8eb2a3666ce4d4d276e1256ca209e2d56 Mon Sep 17 00:00:00 2001 From: "Benjamin J. Culkin" Date: Tue, 17 Jul 2018 18:22:28 -0300 Subject: Add level splitting/contains This allows splitting/contain checking of strings, respecting grouping delimiters. Ex: The string "a|b|(a|b)" would be split into "a", "b", "(a|b)" instead of "a", "b", "(a", "b)" --- .../main/java/bjc/utils/funcutils/StringUtils.java | 85 ++++++++++++++++++++++ 1 file changed, 85 insertions(+) (limited to 'base') diff --git a/base/src/main/java/bjc/utils/funcutils/StringUtils.java b/base/src/main/java/bjc/utils/funcutils/StringUtils.java index 1d0b060..375751c 100644 --- a/base/src/main/java/bjc/utils/funcutils/StringUtils.java +++ b/base/src/main/java/bjc/utils/funcutils/StringUtils.java @@ -254,4 +254,89 @@ public class StringUtils { } return strings; } + + public static boolean levelContains(String haystack, String... needles) { + int nestLevel = 0; + int i = 0; + + while(i < haystack.length()) { + if(nestLevel == 0) { + for(String needle : needles) { + if(haystack.regionMatches(i, needle, 0, needle.length())) { + return true; + } + } + } + + switch(haystack.charAt(i)) { + case '(': + case '[': + case '{': + case '<': + nestLevel += 1; + break; + case ')': + case ']': + case '}': + case '>': + nestLevel = Math.max(0, nestLevel - 1); + break; + } + + i += 1; + } + + return false; + } + + public static List levelSplit(String phrase, String... splits) { + return levelSplit(phrase, false, splits); + } + + public static List levelSplit(String phrase, boolean keepDelims, String... splits) { + String work = phrase; + + List strangs = new ArrayList<>(); + + int nestLevel = 0; + int i = 0; + + while(i < work.length()) { + if(nestLevel == 0) { + for(String split : splits) { + if(work.regionMatches(i, split, 0, split.length())) { + strangs.add(work.substring(0, i)); + + if(keepDelims) strangs.add(split); + + work = work.substring(i + split.length()); + i = 0; + + continue; + } + } + } + + switch(work.charAt(i)) { + case '(': + case '[': + case '{': + case '<': + nestLevel += 1; + break; + case ')': + case ']': + case '}': + case '>': + nestLevel = Math.max(0, nestLevel - 1); + break; + } + + i += 1; + } + + strangs.add(work); + + return strangs; + } } -- cgit v1.2.3