MENU

[Java] How to determine exact match and partial match of a String

当ページのリンクには広告が含まれています。

This is a method of performing complete and partial matches using the matches and contains methods of the String object.

It also describes how to use the startWith method for prefix matching and the endWith method for suffix matching.

TOC

Exact match

Explanation

Exact match only determines that the strings are the same.
Therefore, it judges without using regular expressions.

Example

 

Partial match

Prefix match

Explanation

For prefix match, use “^ (hat mark)”.
*It is called a hat because it is shaped like a hat.

“^” is the symbol that indicates the beginning of the string.
Specifies what string the beginning should match, such as “^123.*”.

If the prefix match part is a fixed value, you can use the startWith method.
In that case, please note that match judgment by regular expression is not possible.

Example

<Supplement>
“. (dot)”
A single character of your choice.
Any character does not matter, but it indicates that there must be one character.
 
“* (asterisk)”
0 or more repetitions of the preceding character.
In other words, “.*” means “.” is repeated 0 or more times.
Since it can be 0 times, it also includes non-repeating patterns.

(example)
Regular expression: ^123.*
Patterns that become True: 123, 1234, 123AAAA

 

Suffix match

Explanation

For backward matching, use “$ (dollar)”.
“$” is the symbol that indicates the end of the string.
Specifies what string the end should match, such as “.*890$”.

If the suffix is a fixed value, you can use the endWith method.
In that case, please note that match judgment by regular expression is not possible.

Example

 

Partial match

Explanation

Use a combination of ‘^’ and ‘$’ for partial matches.
Like “^.*456.*$”.
Surround it with ‘^’ and ‘$’ and allow any character with ‘.*’ before and after the character.

Besides regular expressions, there is also a method using the contains method.
(example)
str4.contains(“444”);
Returns True if the string contains “444”.

Example

 

Conclusion

・Exact match means that the character strings are exactly the same.
・Partial matching includes forward/backward/partial matching.
・Use ^ for prefix match.
・Use $ for suffix matching.
・Regular expressions using ^ and $ or the contains method can be used for partial matching.
・You can specify arbitrary characters with . and * to make flexible judgments.

 

Refer to

[Java Docs] String matches(String regex)

最後までお読み頂き、ありがとうございました!
ご意見・ご要望がありましたら、遠慮なくコメント下さい!

Let's share this post !

Author of this article

Comments

To comment

CAPTCHA


TOC