Home > Enterprise >  Regex all character after first position in Dart
Regex all character after first position in Dart

Time:06-04

I'm trying to achieve this J*** D** from John Doe string but my current code output is **** ***. Here is my current code:

void main() {
  String txt = 'John Doe';
  String hideStr = txt.replaceAll(RegExp(r'\S'), '*');
  print(hideStr);
}

any suggestion?

CodePudding user response:

You can use

String hideStr = txt.replaceAll(RegExp(r'(?<=\S)\S'), '*');

See the regex demo. Details:

  • (?<=\S) - a non-whitespace char is required immediately before the current location
  • \S - a whitespace char.

A non-lookbehind solution is also possible:

String hideStr = txt.replaceAllMapped(RegExp(r'(\S)(\S*)'), 
    (Match m) => "${m[1]}${'*' * (m[2]?.length ?? 0)}");

Details:

  • (\S)(\S*) regex matches and captures into Group 1 a non-whitespace char, and then zero or more whitespace chars are captured into Group 2
  • ${m[1]}${'*' * (m[2]?.length ?? 0)} replacement is a concatenation of
    • ${m[1]} - Group 1 value
    • ${'*' * (m[2]?.length ?? 0)} - a * char repeated the time of Group 2 length. ?? 0 is necessary since m[2]?.length returns a nullable int).

CodePudding user response:

You can use negative look behind to exclude the character at start and after white-space

void main() {
    String txt = 'John Doe';
    String hideStr = txt.replaceAll(RegExp(r'(?<!^|\s)[^\s]'), '*');
    print(hideStr);
}

Because "J" and "D" sit after start of text and a space, the regex won't match it

  • Related