How to truncate a string after n number of words?

The result of the snippet:

How to remove non ASCII characters from a string?

The code snippet below remove the characters from a string that is not inside the range of x20 and x7E ASCII code. The regex below strips non-printable and control characters. But it also keeps the linefeed character \n (x0A) and the carriage return \r (x0D) characters.

Snippet output:

How do I count the number of capturing groups?

Capturing groups are numbered by counting their opening parentheses from left to right. To find out how many groups are present in the expression, call the groupCount() method on a matcher object. The groupCount() method returns an int showing the number of capturing groups present in the matcher’s pattern.

The result of the program: