Skip to content

Commit

Permalink
add Strings#isDigits API
Browse files Browse the repository at this point in the history
inspiration taken from [this SO answer][SO].

note that the steram is not parallelised to avoid the overhead of this
as the method is intended to be called primarily with shorter strings
where the time to set up would take longer than the actual check.

[SO]: https://stackoverflow.com/a/35150400

Signed-off-by: Ralph Ursprung <Ralph.Ursprung@avaloq.com>
  • Loading branch information
rursprung committed Sep 12, 2024
1 parent 330b249 commit 6083330
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
13 changes: 13 additions & 0 deletions libs/core/src/main/java/org/opensearch/core/common/Strings.java
Original file line number Diff line number Diff line change
Expand Up @@ -815,4 +815,17 @@ public static String toLowercaseAscii(String in) {
}
return out.toString();
}

/**
* Check whether every single character in the string is a digit.
*
* Important: this also returns {@code true} for empty strings!
*
* @param s the string, must not be null.
* @return true if the string is empty or only contains digits, false otherwise.
*/
public static boolean isDigits(final String s) {
return s.chars().allMatch(Character::isDigit);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -114,4 +114,14 @@ public void testToStringToXContentWithOrWithoutParams() {
containsString("\"color_from_param\":\"blue\"")
);
}

public void testIsDigits() {
assertTrue(Strings.isDigits(""));
assertTrue(Strings.isDigits("123"));
assertFalse(Strings.isDigits("abc"));
assertFalse(Strings.isDigits("123a"));
assertFalse(Strings.isDigits("0x123"));
assertFalse(Strings.isDigits("123.4"));
assertFalse(Strings.isDigits("123f"));
}
}

0 comments on commit 6083330

Please sign in to comment.