An Interest In:
Web News this Week
- April 19, 2024
- April 18, 2024
- April 17, 2024
- April 16, 2024
- April 15, 2024
- April 14, 2024
- April 13, 2024
April 19, 2024 01:42 am GMT
Original Link: https://dev.to/fluentfuture/string-manipulation-tricks-day-1-2ep1
String Manipulation Tricks (Day 1)
(First post. Don't know what to blog about. I'll start by recording some random coding thought whenever they occur to me and I happen to have time to write it down)
I've recently been thinking about Java string manipulation. Then I stumbled upon this string parsing code:
private static final Pattern THE_NUMBER = Pattern.compile("^\\s\\(([1-9][0-9]*)\\)$");// Find the number from string with header.// example: parseTheNumber("foo", "foo (123)") -> 123// parseTheNumber("foo", "bar (123)") -> empty// parseTheNumber("foo", "foo (str)") -> emptyOptional<Integer> parseTheNumber(String header, String string) { if (!string.startsWith(header)) { return Optional.empty(); } Matcher matcher = THE_NUMBER.matcher( string.substring(header.length())); try { return matcher.matches() ? Optional.of(Integer.parseInt(matcher.group(1))) : Optional.empty(); } catch (NumberFormatException e) { return Optional.empty(); }}
As a racist against Java Regex, I can't help wanting to try it out without regex (using Guava and Mug, my all-in-one toolbox).
import com.google.common.primitives.Ints;import com.google.mu.util.StringFormat;private static final StringFormat THE_NUMBER = new StringFormat("{header} ({num})");Optional<Integer> parseTheNumber(String header, String string) { // StringFormat.parse() will return empty() // if failed to parse, or if the lambda returns null return THE_NUMBER.parse( string, // Ints.tryParse() returns null if failed to parse (h, num) -> h.equals(header) ? Ints.tryParse(num) : null);}
StringFormat
performs well compared to Java regex. And I think it's more readable.
What do you think?
Original Link: https://dev.to/fluentfuture/string-manipulation-tricks-day-1-2ep1
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To