Java两种方法去除字符串末尾的数字
问题:如何去除这个字符串中末尾的数字:sdf12.432fdsf.gfdf32 ?
这个问题的解决关键是要先把字符串进行反转操作。
方法一:
public static String removeNumSuffix1(String source) { if (StringUtils.isBlank(source) || !source.matches(NUM_SUFFIX_REGEX)) { return source; } String reverse = StringUtils.reverse(source); reverse = reverse.replaceFirst(NUM_REGEX, StringUtils.EMPTY); return StringUtils.reverse(reverse); }
方法二:
public static String removeNumSuffix(String source) { if (StringUtils.isBlank(source) || !source.matches(NUM_SUFFIX_REGEX)) { return source; } String reverse = StringUtils.reverse(source); Matcher matcher = NUM_PREFIX_PATTERN.matcher(reverse); if (!matcher.find()) { return source; } String numStr = matcher.group(1); reverse = reverse.replaceFirst(numStr, StringUtils.EMPTY); return StringUtils.reverse(reverse); }
经过测试,两个方法的耗时接近,方法二的耗时略微少一些。
问题:如何去除这个字符串中末尾的数字:sdf12.432fdsf.gfdf32 ? 这个问题的解决关键是要先把字符串进行反转操作。 方法一: public static String removeNumSuffix1(String source) { if (StringUtils.isBlank(source) || !source.matches(NUM_SUFFIX_REGEX)) { return source; } String reverse = StringUtils.reverse(source); reverse = reverse.replaceFirst(NUM_REGEX, StringUtils.EMPTY); return StringUtils.reverse(reverse); } 方法二: public static String removeNumSuffix(String source) { if (StringUtils.isBlank(source) || !source.matches(NUM_SUFFIX_REGEX)) { return source; } String reverse = StringUtils.reverse(source); Matcher matcher = NUM_PREFIX_PATTERN.matcher(reverse); if (!matcher.find()) { return source; } String numStr = matcher.group(1); reverse = reverse.replaceFirst(numStr, StringUtils.EMPTY); return StringUtils.reverse(reverse); } 经过测试,两个方法的耗时接近,方法二的耗时略微少一些。