Class StringParse
- java.lang.Object
-
- Torello.Java.StringParse
-
public class StringParse extends java.lang.Object
A plethora of extensions to Java'sStringclass.
String-Tools which have been written for this'.jar'Library.
Hi-Lited Source-Code:- View Here: Torello/Java/StringParse.java
- Open New Browser-Tab: Torello/Java/StringParse.java
File Size: 44,583 Bytes Line Count: 1,074 '\n' Characters Found
Stateless Class:This class neither contains any program-state, nor can it be instantiated. The@StaticFunctionalAnnotation may also be called 'The Spaghetti Report'.Static-Functionalclasses are, essentially, C-Styled Files, without any constructors or non-static member fields. It is a concept very similar to the Java-Bean's@StatelessAnnotation.
- 1 Constructor(s), 1 declared private, zero-argument constructor
- 52 Method(s), 52 declared static
- 13 Field(s), 13 declared static, 13 declared final
-
-
Field Summary
Regular-Expressions Modifier and Type Field static PatternALPHA_NUMERICstatic PatternCOMMA_REGEXstatic PatternFLOATING_POINT_REGEXstatic PatternNEWLINEPstatic PatternNUMBER_COMMMA_REGEXstatic PatternWHITE_SPACE_REGEXPredicate Modifier and Type Field static Predicate<String>alphaNumPredstatic Predicate<String>floatingPointPredstatic Predicate<String>newLinePredstatic Predicate<String>onlyWhiteSpacestatic Predicate<String>onlyWhiteSpace_OrZeroLenMore Suff Modifier and Type Field static String[]EMPTY_STR_ARRAYstatic StringREG_EX_ESCAPE_CHARS
-
Method Summary
General Methods Modifier and Type Method static StringfindURLRoot(String url)static StringfirstWord(String s)static MatchResult[]getAllMatches(String s, Pattern regEx, boolean eliminateOverlappingMatches)static StringifQuotesStripQuotes(String s)static StringnStrings(String s, int n)static intnumLines(String text)Operations on a Single Java-Character Modifier and Type Method static intcountCharacters(String s, char c)static StringdelChar(String str, int i)static StringnChars(char c, int n)static StringsetChar(String str, int i, char c)The Space-Character ( ' '), and assorted White-Space FunctionsModifier and Type Method static booleanhasWhiteSpace(String s)static StringleftSpacePad(String s, int totalStringLength)static StringremoveDuplicateSpaces(String s)static StringremoveWhiteSpace(String s)static StringrightSpacePad(String s, int totalStringLength)static StringtrimLeft(String s)static StringtrimRight(String s)File & URL Strings: Dot-Dot '../../'Relative-Path String-CalculationModifier and Type Method static StringdotDotParentDirectory(String urlAsStr)static StringdotDotParentDirectory(String directoryStr, char dirSeparator)static StringdotDotParentDirectory(String directoryStr, char separator, short nLevels)static StringdotDotParentDirectory(String urlAsStr, short nLevels)static StringdotDotParentDirectory(URL url)static StringdotDotParentDirectory(URL url, short nLevels)static StringdotDots(String fileName, String ancestorDirectory, char separator)File & URL Strings: The Separator-Character, as defined in java.io.File.separator Modifier and Type Method static StringbeforeLastFileSeparatorPos(String urlOrDir)static intfindLastFileSeparatorPos(String fileOrDir)static StringfromLastFileSeparatorPos(String fileOrDir)File & URL Strings: Extensions - Character-Data occuring after the Period ( '.') CharacterModifier and Type Method static StringbeforeExtension(String file)static intfindExtension(String file, boolean includeDot)static StringfromExtension(String file, boolean includeDot)static StringremoveExtension(String fileNameOrURL)static StringswapExtension(String fileNameOrURLWithExtension, String newExtension)File & URL Strings: Strictly using Front-Slash '/'for the Separator-CharacterModifier and Type Method static StringbeforeLastFrontSlashPos(String urlOrDir)static intfindLastFrontSlashPos(String urlOrDir)static StringfromLastFrontSlashPos(String urlOrDir)Check an Input-String against a Java Numeric-Type Modifier and Type Method static booleanisByte(String s)static booleanisDouble(String s)static booleanisInt(String s)static booleanisInteger(String s)static booleanisLong(String s)protected static booleanisOfPrimitiveType(String s, char[] minArr)static booleanisShort(String s)Base64 Object Serialization Modifier and Type Method static Objectb64MimeStrToObj(String str)static Objectb64StrToObj(String str)static StringobjToB64MimeStr(Object o)static StringobjToB64Str(Object o)Parentheticals Modifier and Type Method static StringremoveAllParenthetical(String s)static StringremoveBraces(String s)static StringremoveBrackets(String s)static StringremoveParens(String s)
-
-
-
Field Detail
-
WHITE_SPACE_REGEX
public static final java.util.regex.Pattern WHITE_SPACE_REGEX
This regular expression simply matches white-space found in a javaString.- See Also:
removeWhiteSpace(String)- Code:
- Exact Field Declaration Expression:
public static final Pattern WHITE_SPACE_REGEX = Pattern.compile("\\s+");
-
onlyWhiteSpace
public static final java.util.function.Predicate<java.lang.String> onlyWhiteSpace
ThisPredicate<String>checks whether the contents of ajava.lang.Stringare comprised of only White-Space Characters.
Java's'asMatchPredicate'is very similar to appending the Reg-Ex Control-Characters'^'and'$'to the beginning and ending of aString.
Important: Since the Regular Expression used is the one defined, above, as\w+- using the'+', rather than the'*'- thisPredicatewill returnFALSEwhen a Zero-LengthStringis passed as input.- See Also:
WHITE_SPACE_REGEX,onlyWhiteSpace_OrZeroLen- Code:
- Exact Field Declaration Expression:
public static final Predicate<String> onlyWhiteSpace = WHITE_SPACE_REGEX.asMatchPredicate();
-
onlyWhiteSpace_OrZeroLen
public static final java.util.function.Predicate<java.lang.String> onlyWhiteSpace_OrZeroLen
This is aPredicatethat works in an identical manner toonlyWhiteSpace, with the minor addded stipulation that a Zero-LengthStringwill generate aTRUE/ pass result from thePredicate.test(String)method.- See Also:
onlyWhiteSpace- Code:
- Exact Field Declaration Expression:
public static final Predicate<String> onlyWhiteSpace_OrZeroLen = Pattern.compile("^\\s*$").asPredicate();
-
COMMA_REGEX
public static final java.util.regex.Pattern COMMA_REGEX
This regular expression simply matches the comma. The only reason for including this here is because the javaclass 'Pattern'contains a method calledStream<String> 'splitAsStream(CharSequence)'which is used for the CSV method further below- See Also:
StrCSV.CSV(String, boolean, boolean),FileRW.readDoublesFromFile(String, boolean, boolean),FileRW.readLongsFromFile(String, boolean, boolean, int)- Code:
- Exact Field Declaration Expression:
public static final Pattern COMMA_REGEX = Pattern.compile(",");
-
NUMBER_COMMMA_REGEX
public static final java.util.regex.Pattern NUMBER_COMMMA_REGEX
This regular expression is used for integer and floating-point numbers that use the comma (',') between the digits that comprise the number. For example, this Regular Expression would match theString"900,800,75.00".- See Also:
FileRW.readIntsFromFile(String, boolean, boolean, int)- Code:
- Exact Field Declaration Expression:
public static final Pattern NUMBER_COMMMA_REGEX = Pattern.compile("(\\d),(\\d)");
-
NEWLINEP
public static final java.util.regex.Pattern NEWLINEP
This represents any version of the new-line character. Note that the'\r\n'version comes before the single'\r'version in the regular-expression, to guarantee that if both are present, they are treated as a single newline.- Code:
- Exact Field Declaration Expression:
public static final Pattern NEWLINEP = Pattern.compile("\\r\\n|\\r|\\n");
-
newLinePred
public static final java.util.function.Predicate<java.lang.String> newLinePred
Predicate for new-line characters- See Also:
NEWLINEP- Code:
- Exact Field Declaration Expression:
public static final Predicate<String> newLinePred = NEWLINEP.asPredicate();
-
REG_EX_ESCAPE_CHARS
public static final java.lang.String REG_EX_ESCAPE_CHARS
This is the list of characters that need to be escaped for a regular expression- See Also:
- Constant Field Values
- Code:
- Exact Field Declaration Expression:
public static final String REG_EX_ESCAPE_CHARS = "\\/()[]{}$^+*?-.";
-
ALPHA_NUMERIC
public static final java.util.regex.Pattern ALPHA_NUMERIC
Alpha-Numeric RegEx- Code:
- Exact Field Declaration Expression:
public static final Pattern ALPHA_NUMERIC = Pattern.compile("^[\\d\\w]*$");
-
alphaNumPred
public static final java.util.function.Predicate<java.lang.String> alphaNumPred
Alpha-NumericStringPredicate.- See Also:
ALPHA_NUMERIC- Code:
- Exact Field Declaration Expression:
public static final Predicate<String> alphaNumPred = ALPHA_NUMERIC.asPredicate();
-
EMPTY_STR_ARRAY
public static final java.lang.String[] EMPTY_STR_ARRAY
An emptyStringarray.- Code:
- Exact Field Declaration Expression:
public static final String[] EMPTY_STR_ARRAY = {};
-
FLOATING_POINT_REGEX
public static final java.util.regex.Pattern FLOATING_POINT_REGEX
A Predicate which uses a regular-expression for checking whether aStringis a valid & parseabledouble, which is guaranteed not to throw aNumberFormatExceptionwhen using the parserDouble.parseDouble.
The Following Description is Directly Copied From:java.lang.Double.valueOf(String), JDK 1.8Leading and trailing whitespace characters in
sare ignored. Whitespace is removed as if by theString.trim()method; that is, both ASCII space and control characters are removed. The rest ofsshould constitute a FloatValue as described by the lexical syntax rules:
where Sign, FloatingPointLiteral, HexNumeral, HexDigits, SignedInteger and FloatTypeSuffix are as defined in the lexical structure sections of The Java™ Language Specification, except that underscores are not accepted between digits. If- FloatValue:
- Signopt
NaN - Signopt
Infinity - Signopt FloatingPointLiteral
- Signopt HexFloatingPointLiteral
- SignedInteger
- HexFloatingPointLiteral:
- HexSignificand BinaryExponent FloatTypeSuffixopt
- HexSignificand:
- HexNumeral
- HexNumeral
. 0xHexDigitsopt.HexDigits0XHexDigitsopt.HexDigits
- BinaryExponent:
- BinaryExponentIndicator SignedInteger
- BinaryExponentIndicator:
pP
sdoes not have the form of a FloatValue, then aNumberFormatExceptionis thrown. Otherwise,sis regarded as representing an exact decimal value in the usual "computerized scientific notation" or as an exact hexadecimal value; this exact numerical value is then conceptually converted to an "infinitely precise" binary value that is then rounded to typedoubleby the usual round-to-nearest rule of IEEE 754 floating-point arithmetic, which includes preserving the sign of a zero value.
Note that the round-to-nearest rule also implies overflow and underflow behaviour; if the exact value ofsis large enough in magnitude (greater than or equal to (Double.MAX_VALUE+Math.ulp(double) ulp(MAX_VALUE)/2), rounding todoublewill result in an infinity and if the exact value ofsis small enough in magnitude (less than or equal toDouble.MIN_VALUE/2), rounding to float will result in a zero.
Finally, after rounding aDoubleobject representing thisdoublevalue is returned.To interpret localized string representations of a floating-point value, use subclasses of
java.text.NumberFormatNote that trailing format specifiers, specifiers that determine the type of a floating-point literal (
1.0fis afloatvalue;1.0dis adoublevalue), do not influence the results of this method. In other words, the numerical value of the input string is converted directly to the target floating-point type. The two-step sequence of conversions, string tofloatfollowed byfloattodouble, is not equivalent to converting a string directly todouble. For example, thefloatliteral0.1fis equal to thedoublevalue0.10000000149011612; thefloatliteral0.1frepresents a different numerical value than thedoubleliteral0.1. (The numerical value 0.1 cannot be exactly represented in a binary floating-point number.)To avoid calling this method on an invalid string and having a
NumberFormatExceptionbe thrown, the regular expression below can be used to screen the input string- See Also:
floatingPointPred,isDouble(String)- Code:
- Exact Field Declaration Expression:
@LinkJavaSource(handle="IOPT", entity=FIELD, name="FLOATING_POINT_REGEX") public static final Pattern FLOATING_POINT_REGEX = IsOfPrimitiveType.FLOATING_POINT_REGEX;
-
floatingPointPred
public static final java.util.function.Predicate<java.lang.String> floatingPointPred
This is the floating-point regular-expression, simply converted to a predicate.- See Also:
FLOATING_POINT_REGEX,isDouble(String)- Code:
- Exact Field Declaration Expression:
@LinkJavaSource(handle="IOPT", entity=FIELD, name="FLOATING_POINT_REGEX") public static final Predicate<String> floatingPointPred = IsOfPrimitiveType.FLOATING_POINT_REGEX.asPredicate();
-
-
Method Detail
-
trimRight
public static java.lang.String trimRight(java.lang.String s)
Trims any white-spaceCharactersfrom the end of aString.Input String: Output String: "A Quick Brown Fox\n \t""A Quick Brown Fox""\tA Lazy Dog.""\tA Lazy Dog."" " (only white-space)"""" (empty-string)""nullthrows NullPointerException- Parameters:
s- Any JavaString- Returns:
- A copy of the same
String- but all characters that matched Java methodjava.lang.Character.isWhitespace(char)and were at the end of theStringwill not be included in the returnedString.
If thezero-length Stringis passed to parameter's', it shall be returned immediately.
If the resultant-Stringhas zero-length, it is returned, without exception. - Code:
- Exact Method Body:
if (s.length() == 0) return s; int pos = s.length(); while ((pos > 0) && Character.isWhitespace(s.charAt(--pos))); if (pos == 0) if (Character.isWhitespace(s.charAt(0))) return ""; return s.substring(0, pos + 1);
-
trimLeft
public static java.lang.String trimLeft(java.lang.String s)
Trims any white-spaceCharactersfrom the beginning of aString.Input String: Output String: "\t A Quick Brown Fox""A Quick Brown Fox""A Lazy Dog. \n\r\t""A Lazy Dog. \n\r\t"" " (only white-space)"""" (empty-string)""nullthrows NullPointerException- Parameters:
s- Any JavaString- Returns:
- A copy of the same
String- but all characters that matched Java methodjava.lang.Character.isWhitespace(char)and were at the start of theStringwill not be included in the returnedString.
If thezero-length Stringis passed to parameter's', it shall be returned immediately.
If the resultant-Stringhas zero-length, it is returned, without exception. - Code:
- Exact Method Body:
int pos = 0; int len = s.length(); if (len == 0) return s; while ((pos < len) && Character.isWhitespace(s.charAt(pos++))); if (pos == len) if (Character.isWhitespace(s.charAt(len-1))) return ""; return s.substring(pos - 1);
-
leftSpacePad
public static java.lang.String leftSpacePad(java.lang.String s, int totalStringLength)
Primarily for convenience in remembering earlier C-styleprintf(...)formatting commands.
This method will "left pad" an inputStringwith spaces, ifs.length() < totalStrLength. If input-parameter's'is equal-to or longer-than the value in'totalStringLength', then the originalStringshall be returned.Input Parameters Returned String "Quick Brown Fox"20" Quick Brown Fox""Hello World"15" Hello World""Write Once, Run Anywhere"10"Write Once, Run Anywhere"nullNullPointerException- Parameters:
s- This may be anyjava.lang.StringtotalStringLength- Ifs.length()is smaller than'totalStringLength', then as many space characters (' ') as are needed to ensure that the returned'String'has length equal to'totalStringLength'will be prepended to the inputStringparameter's'.Ifs.length()is greater than'totalStringLength', then the original input shall be returned.- Throws:
java.lang.IllegalArgumentException- IftotalStringLengthis zero or negative.- See Also:
rightSpacePad(String, int)- Code:
- Exact Method Body:
CHECK_NEGATIVE(totalStringLength); return (s.length() >= totalStringLength) ? s : String.format("%1$" + totalStringLength + "s", s);
-
rightSpacePad
public static java.lang.String rightSpacePad(java.lang.String s, int totalStringLength)
Primarily for convenience in remembering earlier C-styleprintf(...)formatting commands.
This method will "right pad" an inputStringwith spaces, ifs.length() < totalStrLength. If input-parameter's'is equal-to or longer-than the value in'totalStringLength', then the originalStringshall be returned.Input Parameters Returned String "Quick Brown Fox"20"Quick Brown Fox ""Hello World"15"Hello World ""Write Once, Run Anywhere"10"Write Once, Run Anywhere"nullNullPointerException- Parameters:
s- This may be anyjava.lang.StringtotalStringLength- Ifs.length()is smaller than'totalStringLength', then as many space characters (' ') as are needed to ensure that the returned'String'has length equal to'totalStringLength'will be postpended to the inputStringparameter's'.Ifs.length()is greater than'totalStringLength', then the original input shall be returned.- Throws:
java.lang.IllegalArgumentException- IftotalStringLengthis zero or negative.- See Also:
leftSpacePad(String, int)- Code:
- Exact Method Body:
CHECK_NEGATIVE(totalStringLength); return (s.length() >= totalStringLength) ? s : String.format("%1$-" + totalStringLength + "s", s);
-
getAllMatches
public static java.util.regex.MatchResult[] getAllMatches (java.lang.String s, java.util.regex.Pattern regEx, boolean eliminateOverlappingMatches)
Runs a Regular-Expression over aStringto retrieve all matches that occur between inputStringparameter's'and Regular-Expression'regEx'.- Parameters:
s- Any JavaStringregEx- Any Java Regular-ExpressioneliminateOverlappingMatches- When this parameter is passed'TRUE', successive matches that have portions which overlap each-other are eliminated.- Returns:
- An array of all
MatchResult's(from package'java.util.regex.*') that were produced by iterating theMatcher's'find()'method. - Code:
- Exact Method Body:
Stream.Builder<MatchResult> b = Stream.builder(); Matcher m = regEx.matcher(s); int prevEnd = 0; while (m.find()) { MatchResult matchResult = m.toMatchResult(); // This skip any / all overlapping matches - if the user has requested it if (eliminateOverlappingMatches) if (matchResult.start() < prevEnd) continue; b.accept(matchResult); prevEnd = matchResult.end(); } // Convert the Java-Stream into a Java-Array and return the result return b.build().toArray(MatchResult[]::new);
-
setChar
public static java.lang.String setChar(java.lang.String str, int i, char c)
This sets a character in aStringto a new value, and returns a result- Parameters:
str- Any javaStringi- An index into the underlying character array of thatString.c- A new character to be placed at the i'th position of thisString.- Returns:
- a new java
String, with the appropriate index into theStringsubstituted using character parameter'c'. - Code:
- Exact Method Body:
return ((i + 1) < str.length()) ? (str.substring(0, i) + c + str.substring(i + 1)) : (str.substring(0, i) + c);
-
delChar
public static java.lang.String delChar(java.lang.String str, int i)
This removes a character from aString, and returns a newStringas a result.- Parameters:
str- Any Java-String.i- This is the index into the underlying javachar-array whose character will be removed from the returnString.- Returns:
- Since Java
String's are all immutable, thisStringthat is returned is completely new, with the character that was originally at index 'i' removed. - Code:
- Exact Method Body:
if ((i + 1) < str.length()) return str.substring(0, i) + str.substring(i + 1); else return str.substring(0, i);
-
removeDuplicateSpaces
public static java.lang.String removeDuplicateSpaces(java.lang.String s)
Returns the sameStringis input, but trims all spaces down to a single space. Each and every lone / independent or contiguous white-space character is reduced to a single space-character.Input String Output String "This has extra spaces\n""This has extra spaces ""This does not""This does not""\tThis\nhas\ttabs\nand\tnewlines\n"" This has tabs and newlines "- Parameters:
s- Any JavaString- Returns:
- A
Stringwhere all white-space is compacted to a single space. This is generally how HTML works, when it is displayed in a browser. - Code:
- Exact Method Body:
return StringParse.WHITE_SPACE_REGEX.matcher(s).replaceAll(" ");
-
removeWhiteSpace
public static java.lang.String removeWhiteSpace(java.lang.String s)
This string-modify method simply removes any and all white-space matches found within a java-String.Input String Output String "This Has Extra Spaces\n""ThisHasExtraSpaces""This Does Not""ThisDoesNot""\tThis\nHas\tTabs\nAnd\tNewlines\n""ThisHasTabsAndNewlines"- Parameters:
s- AnyString, but if it has any white-space (space that matches regular-expression:\w+) then those character-blocks will be removed- Returns:
- A new
Stringwithout any\w(RegEx for 'whitespace') - See Also:
WHITE_SPACE_REGEX- Code:
- Exact Method Body:
return WHITE_SPACE_REGEX.matcher(s).replaceAll("");
-
nChars
public static java.lang.String nChars(char c, int n)
Generates aStringthat containsncopies of characterc.- Returns:
ncopies ofc, as aString.- Throws:
java.lang.IllegalArgumentException- If the value passed to parameter'n'is negative- See Also:
StrSource.caretBeneath(String, int)- Code:
- Exact Method Body:
if (n < 0) throw new IllegalArgumentException("Value of parameter 'n' is negative: " + n); char[] cArr = new char[n]; Arrays.fill(cArr, c); return new String(cArr);
-
nStrings
public static java.lang.String nStrings(java.lang.String s, int n)
Generates aStringthat containsncopies ofs.- Returns:
ncopies ofsas aString.- Throws:
NException- if the value provided to parameter'n'is negative.- Code:
- Exact Method Body:
if (n < 0) throw new NException("A negative value was passed to 'n' [" + n + ']'); StringBuilder sb = new StringBuilder(); for (int i=0; i < n; i++) sb.append(s); return sb.toString();
-
hasWhiteSpace
public static boolean hasWhiteSpace(java.lang.String s)
This method checks whether or not a java-Stringhas white-space.- Parameters:
s- Any Java-String. If thisStringhas any white-space, this method will returnTRUE- Returns:
TRUEIf there is any white-space in this method, andFALSEotherwise.- See Also:
WHITE_SPACE_REGEX- Code:
- Exact Method Body:
return WHITE_SPACE_REGEX.matcher(s).find();
-
countCharacters
public static int countCharacters(java.lang.String s, char c)
Counts the number of instances of character inputchar ccontained by the inputString s- Parameters:
s- AnyStringcontaining any combination of ASCII/UniCode charactersc- Any ASCII/UniCode character.- Returns:
- The number of times
char coccurs inString s - Code:
- Exact Method Body:
int count = 0; int pos = 0; while ((pos = s.indexOf(c, pos + 1)) != -1) count++; return count;
-
ifQuotesStripQuotes
public static java.lang.String ifQuotesStripQuotes(java.lang.String s)
If theStringpassed to this method contains a single-quote on both sides of theString, or if it contains a double-quote on both sides of thisString, then this method shall return a newStringthat is shorter in length by 2, and leaves off the first and last characters of the input parameterString.
HOPEFULLY, The name of this method explains clearly what this method does- Parameters:
s- This may be any javaString. OnlyString'swhose first and last characters are not only quotation marks (single or double), but also they are the same, identical, quotation marks on each side.- Returns:
- A new
Stringthat whose first and last quotation marks are gone - if they were there when this method began. - Code:
- Exact Method Body:
if (s == null) return null; if (s.length() < 2) return s; int lenM1 = s.length() - 1; // Position of the last character in the String if ( ((s.charAt(0) == '\"') && (s.charAt(lenM1) == '\"')) // String has Double-Quotation-Marks || // ** or *** ((s.charAt(0) == '\'') && (s.charAt(lenM1) == '\'')) ) // String has Single-Quotation-Marks return s.substring(1, lenM1); else return s;
-
numLines
public static int numLines(java.lang.String text)
Counts the number of lines of text inside of a JavaString.- Parameters:
text- This may be any text, as aString.- Returns:
- Returns the number of lines of text. The integer returned shall be precisely
equal to the number of
'\n'characters plus one! - Code:
- Exact Method Body:
if (text.length() == 0) return 0; int pos = -1; int count = 0; do { pos = text.indexOf('\n', pos + 1); count++; } while (pos != -1); return count;
-
findLastFrontSlashPos
public static int findLastFrontSlashPos(java.lang.String urlOrDir)
This function finds the position of the last "front-slash" character'/'in a java-String- Parameters:
urlOrDir- This is any java-String, but preferably one that is aURL, or directory.- Returns:
- The
String-index of the last 'front-slash''/'position in aString, or-1if there are not front-slashes. - Code:
- Exact Method Body:
return urlOrDir.lastIndexOf('/');
-
fromLastFrontSlashPos
public static java.lang.String fromLastFrontSlashPos (java.lang.String urlOrDir)
This returns the contents of aString, after the last front-slash found.
NOTE: If not front-slash'/'character is found, then the originalStringis returned.- Parameters:
urlOrDir- This is any java-String, but preferably one that is aURL, or directory.- Returns:
- the portion of the
Stringafter the final front-slash'/'character. If there are no front-slash characters found in thisString, then the originalStringshall be returned. - Code:
- Exact Method Body:
int pos = urlOrDir.lastIndexOf('/'); if (pos == -1) return urlOrDir; return urlOrDir.substring(pos + 1);
-
beforeLastFrontSlashPos
public static java.lang.String beforeLastFrontSlashPos (java.lang.String urlOrDir)
This returns the contents of aString, before the last front-slash found (including the front-slash'/'itself).
NOTE: If no front-slash'/'character is found, then null is returned.- Parameters:
urlOrDir- This is any java-String, but preferably one that is aURL, or directory.- Returns:
- the portion of the
Stringbefore and including the final front-slash'/'character. If there are no front-slash characters found in thisString, then null. - Code:
- Exact Method Body:
int pos = urlOrDir.lastIndexOf('/'); if (pos == -1) return null; return urlOrDir.substring(0, pos + 1);
-
findLastFileSeparatorPos
public static int findLastFileSeparatorPos(java.lang.String fileOrDir)
This function finds the position of the last'java.io.File.separator'character in a java-String. In UNIX-based systems, this is a forward-slash'/'character, but in Windows-MSDOS, this is a back-slash'\'character. Identifying which of the two is used is obtained by "using" Java'sFile.separatorclass and field.- Parameters:
fileOrDir- This may be any Java-String, but preferably one that represents a file or directory.- Returns:
- The
String-index of the last 'file-separator' position in aString, or-1if there are no such file-separators. - Code:
- Exact Method Body:
return fileOrDir.lastIndexOf(File.separator.charAt(0));
-
fromLastFileSeparatorPos
public static java.lang.String fromLastFileSeparatorPos (java.lang.String fileOrDir)
This returns the contents of aString, after the last'java.io.File.separator'found.
NOTE: If no'java.io.File.separator'character is found, then the originalStringis returned.- Parameters:
fileOrDir- This is any java-String, but preferably one that is a filename or directory-name- Returns:
- the portion of the
Stringafter the final'java.io.File.separator'character. If there are no such characters found, then the originalStringshall be returned. - Code:
- Exact Method Body:
int pos = fileOrDir.lastIndexOf(File.separator.charAt(0)); if (pos == -1) return fileOrDir; return fileOrDir.substring(pos + 1);
-
beforeLastFileSeparatorPos
public static java.lang.String beforeLastFileSeparatorPos (java.lang.String urlOrDir)
This returns the contents of aString, before the last'java.io.File.separator'(including the separator itself).
NOTE: If no'java.io.File.separator'character is found, then null is returned.- Parameters:
urlOrDir- This is any java-String, but preferably one that is aURL, or directory.- Returns:
- the portion of the
Stringbefore and including the final'java.io.File.separator'character. If there are no such characters found in thisString, then null is returned. - Code:
- Exact Method Body:
int pos = urlOrDir.lastIndexOf(File.separator.charAt(0)); if (pos == -1) return null; return urlOrDir.substring(0, pos + 1);
-
swapExtension
public static java.lang.String swapExtension (java.lang.String fileNameOrURLWithExtension, java.lang.String newExtension)
This method swaps the ending 'File Extension' with another, parameter-provided, extension.- Parameters:
fileNameOrURLWithExtension- Any file-name (orURL) that has an extension.newExtension- The file orURLextension used as a substitute for the old extension. ThisStringmay begin with the dot / period character ('.'), and if it does not, one wil be appended.- Returns:
- The new file-name or
URLhaving the substituted extension. - Throws:
StringFormatException- Code:
- Exact Method Body:
final int dotPos = fileNameOrURLWithExtension.lastIndexOf('.'); if (dotPos == -1) throw new StringFormatException( "The file-name provided\n[" + fileNameOrURLWithExtension + "]\n" + "does not have a file-extension" ); if (newExtension.length() == 0) throw new StringFormatException( "The new file-name extension has length 0. " + " To remove an extension, use 'StringParse.removeFileExtension(fileName)'" ); return (newExtension.charAt(0) == '.') ? fileNameOrURLWithExtension.substring(0, dotPos) + newExtension : fileNameOrURLWithExtension.substring(0, dotPos) + '.' + newExtension;
-
removeExtension
public static java.lang.String removeExtension (java.lang.String fileNameOrURL)
This method simply removes all character data after the last identified period character ('.') found withinfileNameOrURL.
If the input-Stringdoes not have a period-character, the originalStringwill be returned, unmodified.- Parameters:
fileNameOrURL- Any file-name orURL, as aString.- Returns:
- The modified file-name, or
URL, as aString.No validity checks of any kind are performed on'fileNameOrURL'. This method merely checks for the presence or absence of a'.'(period-character), and if it finds one, removes everything after-and-including the last-period. - Code:
- Exact Method Body:
final int dotPos = fileNameOrURL.lastIndexOf('.'); return (dotPos == -1) ? fileNameOrURL : fileNameOrURL.substring(0, dotPos);
-
findExtension
public static int findExtension(java.lang.String file, boolean includeDot)
This will return the location within aStringwhere the last period ('.') is found.Caution: No validity checks for valid file-system names are performed. Rather, the portion of the input-Stringstarting at the location of the last period is returned, regardless of what theStringcontains.- Parameters:
file- This may be any Java-String, but preferably one that represents a file.includeDot- When this parameter is passedTRUE, the position-index that is returned will be the location of the last index where a period ('.') is found. WhenFALSE, the index returned will be the location of that period+ 1.- Returns:
- This will return the location of the file-extension. If no period is found, then
-1is returned. If the period is the lastcharin theString, and parameter'includeDot'isFALSE, then-1is returned. - Code:
- Exact Method Body:
int pos = file.lastIndexOf('.'); if (pos == -1) return -1; else if (includeDot) return pos; else if (++pos < file.length()) return pos; else return -1;
-
fromExtension
public static java.lang.String fromExtension(java.lang.String file, boolean includeDot)
This returns the contents of aString, after the last period'.'in thatString. For file-system and web files, this is often referred to as the file extension.
If no period'.'character is found, then null is returned.No validity checks for valid file-system names are performed. Rather, the portion of the input-Stringstarting at the location of the last period is returned, regardless of what theStringcontains.- Parameters:
file- This is any java-String, but preferably one that is a filename.includeDot- Indicates whether the period'.'is to be included in the returned-String.- Returns:
- the portion of the
Stringafter the final period'.'character. If parameterincludeDothas been passedFALSE, then the portion of the input-Stringbeginning after the last period is returned.
If there are no period characters found in thisString, then null is returned. - Code:
- Exact Method Body:
final int pos = findExtension(file, includeDot); return (pos == -1) ? null : file.substring(pos);
-
beforeExtension
public static java.lang.String beforeExtension(java.lang.String file)
This returns the contents of aString, before the last period'.'in thatString. For file-system and web files, this is often referred to as the file extension.
If no period'.'character is found, then the originalStringis returned.Caution: No validity checks for valid file-system names are performed. Rather, the portion of the input-Stringstarting at the location of the last period is returned, regardless of what theStringcontains.- Parameters:
file- This is any java-String, but preferably one that is a filename.- Returns:
- the portion of the
Stringbefore the final period'.'character.
If there are no period characters found in thisString, then the original file is returned. - Code:
- Exact Method Body:
final int pos = file.lastIndexOf('.'); return (pos == -1) ? file : file.substring(0, pos);
-
findURLRoot
public static java.lang.String findURLRoot(java.lang.String url)
This returns the contents of aString, before the last period'.'in thatString. For file-system and web files, this is often referred to as the file extension.
If no period'.'character is found, then the originalStringis returned.Caution: No validity checks for valid file-system names are performed. Rather, the portion of the input-Stringstarting at the location of the last period is returned, regardless of what theStringcontains.- Parameters:
url- A URL as aString- likehttp://domain/directory/[file]- Returns:
- substring(0, index of last front-slash (
'/') inString) - Code:
- Exact Method Body:
final int pos = findLastFrontSlashPos(url); return (pos == -1) ? null : url.substring(0, pos + 1);
-
firstWord
public static java.lang.String firstWord(java.lang.String s)
String text that is situated before the first white-space character in the string.- Returns:
- After breaking the
Stringby white-space, this returns the first 'chunk' before the first whitespace. - Code:
- Exact Method Body:
final int pos = s.indexOf(" "); return (pos == -1) ? s : s.substring(0, pos);
-
removeBrackets
public static java.lang.String removeBrackets(java.lang.String s)
This function will remove any pairs of Brackets within aString, and returned the paired downString- Parameters:
s- AnyString, which may or may not contain a "Bracket Pair"
For Example:- This
Stringdoes contain [a pair of brackets] within! - But this
Stringdoes not.
- This
- Returns:
- The same
String, but with any bracket-pairs removed. - Code:
- Exact Method Body:
return remove_(s, '[', ']');
-
removeBraces
public static java.lang.String removeBraces(java.lang.String s)
Functions the same asremoveBrackets(String)- but removes pairs of curly-braces, insteadNote: These are the'{'curly braces'}'that will be removed from thisString!- Parameters:
s- Any validString{ such as } - (even thisString).
For Example:- This
Stringdoes contain {a pair of curly-braces} within! - But this
Stringdoes not.
- This
- Returns:
- The same
String, but with any curly-brace-pairs removed. - Code:
- Exact Method Body:
return remove_(s, '{', '}');
-
removeParens
public static java.lang.String removeParens(java.lang.String s)
Removes Parenthesis, similar to other parenthetical removing functions.- Parameters:
s- Any (valid)String. Below are sample inputs:
For Example:- This
Stringdoes contain (a pair of parenthesis) within! - But this
Stringdoes not.
- This
- Returns:
- The same
String, but with any parenthesis removed. - Code:
- Exact Method Body:
return remove_(s, '(', ')');
-
removeAllParenthetical
public static java.lang.String removeAllParenthetical(java.lang.String s)
Removes all parenthetical notations. Calls all remove functions- Parameters:
s- Any valid string- Returns:
- The same string, but with all parenthesis, curly-brace & bracket pairs removed.
- See Also:
removeParens(String),removeBraces(String),removeBrackets(String)- Code:
- Exact Method Body:
return removeParens(removeBraces(removeBrackets(s)));
-
objToB64Str
public static java.lang.String objToB64Str(java.lang.Object o) throws java.io.IOException
This will convert any Serializable Java Object into a base-64 String. ThisStringmay be saved, transmitted, even e-mailed to another party, if you wish and decoded else-where. The requirements for this to work are listed here:- Object must implement the
interface java.io.Serializable - Receiving party or storage-device must have access to the
.jar file, or .class file(s)needed to instantiate that object! (You must have shared your classes if you intend to let other people de-serialize instances of that class)
- Parameters:
o- Any javajava.lang.Object. This object must be Serializable, or throws.- Returns:
- A
Stringversion of this object. It will be:- Serialized using the
java.io.ObjectOutputStream(...)object-serialization method - Compressed using the
java.io.GZIPOutputStream(...)stream-compression method - Encoded to a
java.lang.String, via Base-64 Encodingjava.util.Base64.getEncoder()
Compression does not always make much difference, however often times when doing web-scraping projects, there are large Javajava.util.Vectorfilled with many lines of text, and these lists may be instantly and easily saved using object-serialization. Furthermore, in these cases, the compression will sometimes reduce file-size by an order of magnitude. - Serialized using the
- Throws:
java.io.IOException- See Also:
b64StrToObj(String)- Code:
- Exact Method Body:
return B64.objToB64Str(o);
- Object must implement the
-
b64StrToObj
public static java.lang.Object b64StrToObj(java.lang.String str) throws java.io.IOException
This converts to any java.io.Serializable object from a compressed, serialized, Base-64 Encodedjava.lang.String. This method can be thought of as one which converts objects which have been previously encoded as aString, and possibly even transmitted across the internet, back into an JavaObject.Requirements TheObjectthat is to be instantiated must have its class files accessible to the class-loader. This is the exact-same requirement expected by all Java "de-serializations" routines.- Parameters:
str- Any previously Base-64 encoded, serialized, compressedjava.lang.Object'that has been saved as aString. ThatStringshould have been generated using theProgramming.objToB64Str(Object o)method in this class.- Serialized using the
java.io.ObjectOutputStream(...)object-serialization method - Compressed using the
java.io.GZIPOutputStream(...)sream-compression method - Encoded to a
String, via Base-64 Encodingjava.util.Base64.getEncoder()
Compression does not always make much difference, however often times when doing web-scraping projects, there are large Javajava.util.Vectorfilled with many lines of text, and these lists may be instantly and easily saved using object-serialization. Furthermore, in these cases, the compression will sometimes reduce file-size by an order of magnitude.- Serialized using the
- Returns:
- A de-compressed
java.lang.Objectconverted back from a B64-String - Throws:
java.io.IOException- See Also:
objToB64Str(Object)- Code:
- Exact Method Body:
return B64.b64StrToObj(str);
-
objToB64MimeStr
public static java.lang.String objToB64MimeStr(java.lang.Object o) throws java.io.IOException
This performs an identical operation as the method:objToB64Str, however it generates an outputStringthat is "MIME" compatible. All this means is that theStringitself - which could conceivable by thousands or even hundreds of thousands of characters long - will havenew-line charactersinserted such that it may be printed on paper or included in a text-file that is (slightly) more human-readable. Base64 MIME encodedString'slook like very long paragraphs of random-text data, while regular Base64-encodings are a single, very-long,Stringwith no space characters.- Parameters:
o- Anyjava.lang.Object. This object must be Serializable, or else the code will generate an exception.- Returns:
- A Base-64 MIME-Encoded
Stringof any serializablejava.lang.Object - Throws:
java.io.IOException- See Also:
objToB64Str(Object),b64MimeStrToObj(String)- Code:
- Exact Method Body:
return B64.objToB64MimeStr(o);
-
b64MimeStrToObj
public static java.lang.Object b64MimeStrToObj(java.lang.String str) throws java.io.IOException
This performs an identical operation as the method:b64StrToObj, however receives a "MIME" compatible encodedString. All this means is that theStringitself - which could conceivable by thousands or even hundreds of thousands of characters long - will havenew-line charactersinserted such that it may be printed on paper or included in a text-file that is (slightly) more human-readable. Base64 MIME encodedString'slook like very long paragraphs of random-text data, while regular Base64 encodings a single, very-long,String's.- Returns:
- The (de-serialized) java object that was read from the input parameter
String 'str'Requirements: The object that is to be instantiated must have its class files accessible to the class-loader. This is the exact-same requirement expected by all Java "de-serializations" routines. - Throws:
java.io.IOException- See Also:
b64StrToObj(String),objToB64MimeStr(Object)- Code:
- Exact Method Body:
return B64.b64MimeStrToObj(str);
-
dotDots
public static java.lang.String dotDots(java.lang.String fileName, java.lang.String ancestorDirectory, char separator)
Computes a "relativeURL String".- Parameters:
fileName- This is a fileName whose ancestor directory needs to be relative-izedancestorDirectory- This is an ancestor (container) directory.separator- The separator character used to separate file-system directory names.- Returns:
- This shall return the
"../.."structure needed to insert a relative-URLor link into a web-page. - Throws:
java.lang.IllegalArgumentException- This exception shall throw if the separator character is not one of the standard file & directory separators: forward-slash'/'or back-slash'\'.This exception also throws if theStringprovided to parameter'fileName'does not begin-with theStringprovided to parameter'ancestorDirectory'.- Code:
- Exact Method Body:
return DotDots.specifiedAncestor(fileName, ancestorDirectory, separator);
-
dotDotParentDirectory
public static java.lang.String dotDotParentDirectory(java.net.URL url)
Rerieve the Parent-Directory of a URLSee Docs: Method dotDotParentDirectory(String, char, short)Converts: Input URLto aString- eliminates non-essentialURI-information (Such as:Query-Strings, and others as well)Passes: Character char '/', the separator character used inURL'sPasses: A '1'to parameter'nLevels'- only going up one directory- Code:
- Exact Method Body:
final String urlStr = url.getProtocol() + "://" + url.getHost() + url.getPath(); return DotDots.parentDir(urlStr, '/', (short) 1);
-
dotDotParentDirectory
public static java.lang.String dotDotParentDirectory (java.lang.String urlAsStr)
Rerieve the Parent-Directory of a URL as a StringSee Docs: Method dotDotParentDirectory(String, char, short)Passes: char '/', the separator character used inURL'sPasses: '1'to parameter'nLevels'- only going up on directory- Code:
- Exact Method Body:
return DotDots.parentDir(urlAsStr, '/', (short) 1);
-
dotDotParentDirectory
public static java.lang.String dotDotParentDirectory(java.net.URL url, short nLevels)
Rerieve the nth Ancestory-Directory of a URLSee Docs: Method dotDotParentDirectory(String, char, short)Converts: URLtoString, eliminates non-essentialURI-information (such as Query-Strings, etc.)Passes: A Separator-Character char '/'- the separator used inURL's- Code:
- Exact Method Body:
final String urlStr = url.getProtocol() + "://" + url.getHost() + url.getPath(); return DotDots.parentDir(urlStr, '/', nLevels);
-
dotDotParentDirectory
public static java.lang.String dotDotParentDirectory (java.lang.String urlAsStr, short nLevels)
Rerieve the nth Ancestory-Directory of a URL as a StringSee Docs: Method dotDotParentDirectory(String, char, short)Passes: char '/', the separator character used inURL's- Code:
- Exact Method Body:
return DotDots.parentDir(urlAsStr, '/', nLevels);
-
dotDotParentDirectory
public static java.lang.String dotDotParentDirectory (java.lang.String directoryStr, char dirSeparator)
Rerieve the Parent-Directory from String, use a Specified Separator-CharSee Docs: Method dotDotParentDirectory(String, char, short)Passes: '1'to parameternLevels- only going up one directory.- Code:
- Exact Method Body:
return DotDots.parentDir(directoryStr, dirSeparator, (short) 1);
-
dotDotParentDirectory
public static java.lang.String dotDotParentDirectory (java.lang.String directoryStr, char separator, short nLevels)
This does traverses up a directory-tree structure, and returns a 'parent-level' directory that is'nLevels'up the tree.Reminder: The character used as the "File Separator" and/or "Directory Separator" can be obtained using the field:java.io.File.Separator.charAt(0).The classjava.io.Fileprovides access to the file-separator used by the file-system on which the JVM is currently running, although it treats it as a multi-characterString.
There is no error-checking performed by this method regarding whether the inputStringrepresents a valid file or directory. Instead, this method just looks for the second from last separator-character (usually a'/'forward-slash char) and returns a substring that starts at index 0, and continues to that position-plus-1 (in order to include that second-to-last separator char).- Parameters:
directoryStr- This may be any java-String, although it is expected to be on which represents the file & directory structure of file on the file-system. It may also beURLfor a web-siteseparator- This is the separator currently used by that file & directory system. If trying to find the parent directory of aURL, this should be the forward-slash character'/'.nLevels- This is how many "parent-level directories" (how many levels up the tree) need to be computed. This parameter must '1' or greater. If the passed parameter'directoryStr'does not contain enough directories to traverse up the tree, then this method will throw anIllegalArgumentException.- Returns:
- a
Stringthat represents 'nLevels' up the directory tree, either for a directory on the local-file system, or on a web-server from a Uniform Resource Locator. - Throws:
java.lang.IllegalArgumentException- If the value of parametershort 'nLevels'is negative, or does not identify a number consistent with the number of directories that are contained by the input urlAsStr parameter.This exception shall also throw if the'separator'character is not one of the standard file & directory separators: forward-slash'/'or back-slash'\'.- Code:
- Exact Method Body:
return DotDots.parentDir(directoryStr, separator, nLevels);
-
isInteger
public static boolean isInteger(java.lang.String s)
Determines, efficiently, whether an inputStringis also an integer.A leading plus-sign ('+') will, in fact, generate aFALSEreturn-value for this method.- Parameters:
s- Any javaString- Returns:
TRUEif the inputStringis any integer, and false otherwise.
This method does not check whether the number, itself, will actually fit into a field or variable of type'int'. For example, the inputString '12345678901234567890'(a very large integer), though an integer from a mathematical perspective, is not a valid java'int'. In such cases,TRUEis returned, but if Java'sInteger.parseIntmethod were subsequently used, that method would throw an exception.The primary purpose of this method is to avoid having to writetry {} catch (NumberFormatException)code-blocks. Furthermore, if only a check is desired, and theStringdoes not actually need to be converted to a number, this is also more efficient than actually performing the conversion.- See Also:
isInt(String)- Code:
- Exact Method Body:
return IsOfPrimitiveType.isInteger(s);
-
isInt
public static boolean isInt(java.lang.String s)
Check if a Java-String Comprises a Valid IntegerPasses: The ASCII characters that comprise Integer.MIN_VALUE- Code:
- Exact Method Body:
return IsOfPrimitiveType.check(s, IsOfPrimitiveType.INT_MIN_VALUE_DIGITS_AS_CHARS);
-
isLong
public static boolean isLong(java.lang.String s)
Check if a Java-String Comprises a Valid Long-IntegerPasses: The ASCII characters that comprise Long.MIN_VALUE- Code:
- Exact Method Body:
return IsOfPrimitiveType.check(s, IsOfPrimitiveType.LONG_MIN_VALUE_DIGITS_AS_CHARS);
-
isByte
public static boolean isByte(java.lang.String s)
Check if a Java-String Comprises a Valid BytePasses: ASCII characters that comprise Byte.MIN_VALUE- Code:
- Exact Method Body:
return IsOfPrimitiveType.check(s, IsOfPrimitiveType.BYTE_MIN_VALUE_DIGITS_AS_CHARS);
-
isShort
public static boolean isShort(java.lang.String s)
Check if a Java-String Comprises a Valid Short-IntegerPasses: ASCII characters that comprise Short.MIN_VALUE- Code:
- Exact Method Body:
return IsOfPrimitiveType.check(s, IsOfPrimitiveType.SHORT_MIN_VALUE_DIGITS_AS_CHARS);
-
isOfPrimitiveType
protected static boolean isOfPrimitiveType(java.lang.String s, char[] minArr)
Determines whether the inputStringis an integer in the range of Java's primitive type specified by an inputchar[]array parameter. Specifically, if the the inputStringis both a mathematical integer, and also an integer in the range ofMIN_VALUEandMAX_VALUEfor that primitive-type and then (and only then) willTRUEbe returned.Note: The max and min values in which the range of valid integers must reside (for primitive-type'int', for instance) are as below:-2147483648...2147483647.
Furthermore: A leading plus-sign ('+') will, in fact, generate aFALSEreturn-value for this method.- Parameters:
s- Any JavaStringminArr- The value of a Java PrimitiveMIN_VALUE, without the minus-sign, represented as achar[]array.Primitive Type Integer as ASCII char[]arraybyte'2', '5', '6'short'6', '5', '5', '3', '6'int'2', '1', '4', '7,' '4', '8', '3', '6', '4', '8'long'2', '1', '4', '9', '2', '2', '3', '3', '7', '2', '0', '3', '6', '8', '5', '4', '7', '7', '5', '8', '0', '8'- Returns:
TRUEIf the inputStringis both an integer, and also one which falls in the range comprised by the specified Java Primitive Type. ReturnFALSEotherwise.The primary purpose of this method is to avoid having to writetry {} catch (NumberFormatException)code-blocks. Furthermore, if only a check is desired, and theStringdoes not actually need to be converted to a number, this is also more efficient than actually performing the conversion.- See Also:
isInteger(String),isInt(String),isByte(String),isLong(String),isShort(String)- Code:
- Exact Method Body:
return IsOfPrimitiveType.check(s, minArr);
-
isDouble
public static boolean isDouble(java.lang.String s)
Tests whether an input-Stringcan be parsed into adouble- Returns:
- See Also:
FLOATING_POINT_REGEX,floatingPointPred- Code:
- Exact Method Body:
return floatingPointPred.test(s);
-
-