Java - String.replaceAll replace all non-pattern characters

I have a Java regex:

^[a-zA-Z_][a-zA-Z0-9_]{1,126}$

It means:

  • Start with an alphabet or underscore.
  • Subsequent characters may contain letters, numbers or underscores.
  • Length is from 1 to 127 characters.

Now I want to replace the string with characters not in this regular expression with underscore.

Example:

final String label = "23_fgh99@#";
System.out.println(label.replaceAll("^[^a-zA-Z_][^a-zA-Z0-9_]{1,126}$", "_"));

But the result is still 23_fgh99@#.

How can I "convert" it to _3_fgh99__?

+4
source share
1 answer

Use this code :

final String label = "23_fgh99@#";
System.out.println(label.replaceAll("^[^a-zA-Z_]|(?<!^)[^a-zA-Z0-9_]", "_"));

He deduces _3_fgh99__.

, " ", (^[^a-zA-Z_]), ((?<!^)[^a-zA-Z0-9_]). | 1 .

+3

Source: https://habr.com/ru/post/1589183/


All Articles