Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Beginning Regular Expressions 2005.pdf
Скачиваний:
95
Добавлен:
17.08.2013
Размер:
25.42 Mб
Скачать

Chapter 25

Using the replaceAll() Method

The String class’s replaceAll() method replaces all matches for a regular expression with a specified replacement string. The first argument of replaceAll() is a String containing the regular expression pattern. The second argument is a String containing the replacement string.

Using the split() Method

The String class’s split() method may be used with one argument or two. It is used to split a string into substrings. The place of the split is defined by the regular expression. It returns a String array.

When used with one argument, the argument is a String containing a regular expression pattern. At each occurrence of the pattern, the test string is split into substrings. When used with two arguments, the first argument is a String containing a regular expression. The second argument is an int value that specifies a maximum number of splits to take place. Subject to the limit imposed by the second argument, the test string is split into substrings at each occurrence of the pattern. If the regular expression pattern contains an error, a PatternSyntaxException is raised.

Exercises

The following exercises allow you to test your understanding of some aspects of the material covered in this chapter:

1.Modify the replaceAll.java code so that only the first occurrence of a match for the regular expression pattern is replaced.

2.Modify the stringReplaceFirst.java code so that all occurrences of the character sequence twinkle are replaced.

658