-2

UUID.randomUUID().toString().replaceAll(“\W”, “”);

What does the meaning of “\W” in the above statement? Is it replace non-alphanumerics? This replaceAll method changing the entire generated random value. Let’s say 1. UUID.randomUUID().toString() 2. UUID.randomUUID().toString().replaceAll(“\W”, “”); Both 1& 2 values are totally different Please advise . Thanks in advance for your response

pchand
  • 25
  • 5
  • What do you think `randomUUID()` is doing? Especially if you call it twice. – Henry Feb 04 '18 at 08:12
  • Can't you just test these code snippets locally and see for yourself what they are doing? Replacing `\\W+` with empty string will in fact strip off non alphanumerics, which in this case would be the hyphen separators of the UUID. – Tim Biegeleisen Feb 04 '18 at 08:19
  • Have you read [this question](https://stackoverflow.com/questions/4736/learning-regular-expressions)? – user202729 Feb 04 '18 at 08:21

1 Answers1

2

As Java API Documentation states:

String.replaceAll(String regex, String replacement)

Replaces each substring of this string that matches the given regular expression with the given replacement.

As you see, first argument is a regular expression. To see list of available ways of using regular expressions, you can look up Pattern class in documentation:

https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html

You will find that \\W looks for a non-word character. In your particular example it means replacing "-" with "", in other words, you get rid of all "-" from UUID passed to that method.

Przemysław Moskal
  • 3,551
  • 2
  • 12
  • 21