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 stream 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 <[email protected]>
  • Loading branch information
rursprung committed Sep 13, 2024
1 parent 330b249 commit ea0f6aa
Show file tree
Hide file tree
Showing 2 changed files with 24 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.
*
* <p>An empty string returns {@code false}.</p>
*
* @param s the string, must not be null.
* @return {@code true} if the string only contains digits, {@code false} otherwise.
*/
public static boolean isDigits(final String s) {
return !s.isEmpty() && s.chars().allMatch(Character::isDigit);
}

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

public void testIsDigits() {
assertTrue(Strings.isDigits("1"));
assertTrue(Strings.isDigits("123"));
assertFalse(Strings.isDigits(""));
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 ea0f6aa

Please sign in to comment.