How kotlin builds regular expressions with regex

preface

I believe many people know about regular expressions, but many people's first feeling is that they are difficult to learn, because at first glance, they feel that there is no law to find, and they are all a pile of various special symbols, completely confused.

In fact, it's just that you don't know regular. After understanding it, you'll find that it's like this ~ ~ there are not many relevant characters used in regular. It's not difficult to remember and understand. The only difficulty is that after they are combined, they are not readable and easy to understand. Recently, I'm learning kotlin. Kotlin provides a regular expression class regex. Let's learn together.

Regex provides rich, simple and practical functions.

matches

All input strings match "regular expression" and return true; otherwise, return false.

Operation results

containsMatchIn

If at least one of the input strings matches, it will return true, otherwise it will return false.

Operation results

matchEntire

Compare all strings and return a matchermatchresult object if they match the regular expression. Otherwise, return null.

When we use the value value of matchermatchresult to display the matching result, because the matchentire function may return a null, the safe call symbol "?" is used here.

Operation results

replace

replace(input: CharSequence,replacement: String): String

Replace the matching part of the input string with the content of the replacement.

This example is to replace the number with ABCD.

Replace function

Function signature: replace (input: charsequence, transform: (matchresult) - > charsequence): String

Its function is to replace the matching value in the input string with the new value mapped by the function transform.

We can see that there are two numbers in the input string, one is 12 at the front of the string and the other is 9 at the back of the string.

Operation results

12 was replaced with 144 and 9 was replaced with 81.

Find function

Returns the first matching matchresult object in a string

This code will match 123, and the result displayed by using the value value is easier for us to understand.

Operation results

findAll

Returns the matchresult sequence of all matching values in the input string.

We can iterate through the foreach loop to display all matching results

Operation results

summary

The above is the whole content of this article. I hope the content of this article has a certain reference value for your study or work. If you have any questions, you can leave a message. Thank you for your support for programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>