代码之家  ›  专栏  ›  技术社区  ›  Julian

用于从字符串中提取所有标题数字的正则表达式

  •  0
  • Julian  · 技术社区  · 3 年前

    我正在尝试使用Java正则表达式从字符串中提取所有标题数字,而无需编写其他代码,但我找不到可以工作的内容:

    "12345XYZ6789ABC" "12345" .
    "X12345XYZ6789ABC" 你什么也不给我

    public final class NumberExtractor {
        private static final Pattern DIGITS = Pattern.compile("what should be my regex here?");
    
        public static Optional<Long> headNumber(String token) {
            var matcher = DIGITS.matcher(token);
            return matcher.find() ? Optional.of(Long.valueOf(matcher.group())) : Optional.empty();
        }
    }
    
    2 回复  |  直到 3 年前
        1
  •  1
  •   Bohemian    3 年前

    使用 \b :

    \b\d+
    

    看见 live demo .

    如果您严格希望只匹配输入开头的数字,而不是每个单词的数字(当输入仅包含一个单词时是同一件事),请使用 ^ :

    ^\d+
    

    Pattern DIGITS = Pattern.compile("\\b\\d+"); // leading digits of all words
    Pattern DIGITS = Pattern.compile("^\\d+"); // leading digits of input
    
        2
  •  -1
  •   user3486184    3 年前