yonan2236
yonan2236

Reputation: 13649

How to Determine if a String starts with exact number of zeros?

How can I know if my string exactly starts with {n} number of leading zeros? For example below, the conditions would return true but my real intention is to check if the string actually starts with only 2 zeros.

String str = "00063350449370"

if (str.startsWith("00")) { // true
    ...
}

Upvotes: 1

Views: 8172

Answers (7)

Mike
Mike

Reputation: 3311

The long way

    String TestString = "0000123";
    Pattern p = Pattern.compile("\\A0+(?=\\d)");
    Matcher matcher = p.matcher(TestString);

    while (matcher.find()) {
          System.out.print("Start index: " + matcher.start());
          System.out.print(" End index: " + matcher.end() + " ");
          System.out.println(" Group: " + matcher.group());
    }

Your probably better off with a small for loop though

    int leadZeroes;
    for (leadZeroes=0; leadZeroes<TestString.length(); leadZeroes++)
        if (TestString.charAt(leadZeroes) != '0')
            break;

    System.out.println("Count of Leading Zeroes: " + leadZeroes);

Upvotes: 0

hfontanez
hfontanez

Reputation: 6168

You can use a regular expression to evaluate the String value:

String str = "00063350449370";
String pattern = "[0]{2}[1-9]{1}[0-9]*"; // [0]{2}[1-9]{1} starts with 2 zeros, followed by a non-zero value, and maybe some other numbers: [0-9]*
if (Pattern.matches(pattern, str))
{
    // DO SOMETHING
}

There might be a better regular expression to resolve this, but this should give you a general idea how to proceed if you choose the regular expression path.

Upvotes: 0

user1038550
user1038550

Reputation:

How about using a regular expression?

0{n}[^0]*

where n is the number of leading '0's you want. You can utilise the Java regex API to check if the input matches the expression:

Pattern pattern = Pattern.compile("0{2}[^0]*"); // n = 2 here
Matcher matcher = pattern.matcher(input);
if (matcher.matches()) {
    // code
}

Upvotes: 1

Joop Eggen
Joop Eggen

Reputation: 109547

Slow but:

if (str.matches("(?s)0{3}([^0].*)?") {

This uses (?s) DOTALL option to let . also match line-breaks.

0{3} is for 3 matches.

Upvotes: 1

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

You can try this regex

boolean res = s.matches("00[^0]*");

Upvotes: 2

RealSkeptic
RealSkeptic

Reputation: 34618

You can do something like:

if ( str.startsWith("00") && ! str.startsWith("000") ) {
   // ..
}

This will make sure that the string starts with "00", but not a longer string of zeros.

Upvotes: 11

xp500
xp500

Reputation: 1426

How about?

final String zeroes = "00";
final String zeroesLength = zeroes.length();
str.startsWith(zeroes) && (str.length() == zeroes.length() || str.charAt(zeroes.length()) != '0')

Upvotes: 1

Related Questions