简体   繁体   中英

regex to replace digits of a number with 0 (after 6th digit and before last 4th digit)

Need a regular expression To replace digits of a number with '0' after 6th digit and before last 4 digits. like

Input : 11111111111111     Output : 11111100001111
Input : 1234567878789999   Output : 1234560000009999

I tried regex:' ^([0-9]{6})([^0]+)([0-9]{4})$ ' .

    int count = 0;
    String inputNumber = "1234567878789999";
    String convertedNum = "";
    Pattern pattrn = Pattern.compile("(\\d|\\D)");
    System.out.println(inputNumber);
    Matcher m = pattrn.matcher(inputNumber);

    while (m.find()) {
        Pattern pattern1 = Pattern.compile("(\\d)");
        Matcher m1 = pattern1.matcher(m.group());
        if (m1.find()) {
            count++;
            if (count > 6 && count < inputNumber.length()-4){
                convertedNum = convertedNum +  m.group().replace(m.group(), "#");
            }else{
                convertedNum = convertedNum +m.group();
            }
        } else{
            convertedNum = convertedNum +m.group();
        }
    }
    System.out.println("convertedNum : "+ convertedNum);

Try this:

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Regex {
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String num_string  = sc.nextLine();
    String patternString = "(?<=[0-9]{6})([0-9])(?=[0-9]{4})";
    Pattern pattern = Pattern.compile(patternString);

    Matcher matcher = pattern.matcher(num_string);
    String answer = matcher.replaceAll("0");
    System.out.println(answer);

    }
}

This one will give you what you want:

Pattern pattern = Pattern.compile("^(\\d{6})(\\d+)(\\d{4})$");
Matcher matcher = pattern.matcher("1234567878789999");

if (matcher.find()) {
    StringBuilder sb = new StringBuilder();
    sb.append(matcher.group(1));
    for (int i = 0; i < matcher.group(2).length(); i++) {
        sb.append('0');
    }
    sb.append(matcher.group(3));
    System.out.println(sb.toString()); //prints 1234560000009999
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM