You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中匹配包含数字及至少一个星号的正则表达式求解

Solution for Regex Matching Strings with Digits and Asterisks

Got it, let's sort out this regex issue for you! Your current approach with \d doesn't work because Pattern.matches() requires the entire string to match the regex, and \d only matches a single digit. Plus, it doesn't check for the required asterisk at all.

Correct Regex Pattern

To ensure a string contains at least one digit and at least one asterisk, use this regex:

^(?=.*\d)(?=.*\*).+$

Breakdown of the Pattern

Let's break down what each part does:

  • ^: Anchors the match to the start of the string
  • (?=.*\d): Positive lookahead that checks if there's at least one digit (\d) anywhere in the string
  • (?=.*\*): Another positive lookahead that checks for at least one asterisk (we escape it with \* because * is a special regex character)
  • .+: Matches any character (except newlines) one or more times, ensuring the string isn't empty
  • $: Anchors the match to the end of the string (reinforces that we're matching the entire string)

Updated Test Code

Here's the corrected Java code to test this pattern against your cases:

import java.util.regex.Pattern;

public class RegexValidation {
    public static void main(String[] args) {
        String validRegex = "^(?=.*\\d)(?=.*\\*).+$";
        
        // Test cases
        System.out.println(Pattern.matches(validRegex, "12345678*"));   // true (has digits + asterisk)
        System.out.println(Pattern.matches(validRegex, "1234****"));     // true (has digits + asterisk)
        System.out.println(Pattern.matches(validRegex, "123456789"));    // false (no asterisk)
        System.out.println(Pattern.matches(validRegex, "abc45678*"));    // true (has digits + asterisk)
        System.out.println(Pattern.matches(validRegex, "abc****"));      // false (no digits)
        System.out.println(Pattern.matches(validRegex, "*123xyz"));      // true (has digits + asterisk)
    }
}

Alternative (Without Lookaheads)

If you prefer a pattern without lookaheads, you can use this version that checks for either digit-then-asterisk or asterisk-then-digit:

^.*(\d.*\*|\*.*\d).*$

The lookahead version is generally more readable and easier to modify if you need to add more requirements later.

Notes

  • If your strings might contain newline characters, replace . with [\s\S] (matches all whitespace and non-whitespace characters) to cover those cases.
  • The pattern ensures the string has both required characters—neither a string with only digits nor only asterisks will pass.

内容的提问来源于stack exchange,提问作者Nirali Joshi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 18:27:42