String manipulation and regular expressions are essential techniques for working with textual data in programming. In Java, you can perform various operations on strings using built-in methods, and regular expressions provide a powerful way to search, manipulate, and validate strings based on patterns.
String Manipulation
1. Concatenation
You can concatenate strings using the `+` operator or the `concat()` method.
String str2 = "World";
String result = str1 + ", " + str2; // Using +
String result2 = str1.concat(", ").concat(str2); // Using concat()
2. Length
You can get the length of a string using the `length()` method.
int length = str.length(); // length is 13
3. Substring
You can extract a substring from a string using the `substring()` method.
String substring = str.substring(7); // substring is "World!"
4. Splitting
You can split a string into an array of substrings using the `split()` method.
String[] fruits = str.split(",");
// fruits is {"apple", "orange", "banana"}
5. Replace
You can replace characters or substrings in a string using the `replace()` method.
String replaced = str.replace("Hello", "Hi");
// replaced is "Hi, World!"
Regular Expressions
Regular expressions (regex) are patterns used to match character combinations in strings.
1. Matching
You can check if a string matches a specific pattern using the `matches()` method.
boolean matches = str.matches("Hello.*");
// matches is true
2. Searching
You can search for occurrences of a pattern within a string using `Pattern` and `Matcher` classes.
String str = "The cat and the mat.";
Pattern pattern = Pattern.compile("cat");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println("Found at index: " + matcher.start());
}
// Output: Found at index: 4
3. Splitting
You can split a string using a regex pattern.
String[] fruits = str.split("[,;]");
// fruits is {"apple", "orange", "banana"}
4. Replacement
You can replace parts of a string based on a pattern.
String replaced = str.replaceAll("\\s", ",");
// replaced is "apple,orange,banana"
Regular expressions offer a flexible and powerful way to manipulate strings, but they can be complex and require careful attention to syntax. Java provides comprehensive support for regular expressions through the `java.util.regex` package.
Nenhum comentário:
Postar um comentário