[Java tutorial] use case-insensitive Java lookup alternatives

Source: Internet
Author: User

Author: gnuhpc
Source: http://www.cnblogs.com/gnuhpc/

The regular expression can be used to construct the front edge of the string to be searched (? (I), which indicates that it is case insensitive. For example, to search for here, the structure (? I) Here, which indicates here, and so on. However, this will also match there. We can also add a delimiter to indicate a separate here word,/B (? I) Here/B. Use the string matches () method for matching. The replaceall () method is used for replacement.

The preceding two methods handle exceptions. This is ignored in the small example below.

// Ignore case differences when searching
// Or replacing substrings.
Class ignorecasedemo {
Public static void main (string ARGs []) {
String STR = "this is a test .";
System. Out. println ("ignore case when searching./N" +
"Looking for 'test' in:" + Str );
// Use matches () to find any version of test.
If (Str. Matches ("(? I). * test .*"))
System. Out. println ("test is in the string .");
System. Out. println ();
STR = "Alpha Beta, Alpha Beta ";

// Use replaceall () to ignore case when replacing one
// Substring with another.
// In this example, replace all versions of alpha with ETA.
System. Out. println ("ignore case when replacing./N" +
"Replace any version of 'alpha'" +
"With 'za' in:/N" + "" + Str );
String result = Str. replaceall ("(? I) Alpha "," ETA ");
System. Out. println ("after replacement:/N" +
"" + Result );
}
}

Of course, this is not the only method. The regionmatches () method can also be used. If it is not too troublesome, You can first convert the string to lowercase, and then use the contains () method to determine whether a substring exists.

To replace the first appearance, use the replacefirst () method.

 

Author: gnuhpc
Source: http://www.cnblogs.com/gnuhpc/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.