Book Image

Java 9 Regular Expressions

By : Anubhava Srivastava
Book Image

Java 9 Regular Expressions

By: Anubhava Srivastava

Overview of this book

Regular expressions are a powerful tool in the programmer's toolbox and allow pattern matching. They are also used for manipulating text and data. This book will provide you with the know-how (and practical examples) to solve real-world problems using regex in Java. You will begin by discovering what regular expressions are and how they work with Java. This easy-to-follow guide is a great place from which to familiarize yourself with the core concepts of regular expressions and to master its implementation with the features of Java 9. You will learn how to match, extract, and transform text by matching specific words, characters, and patterns. You will learn when and where to apply the methods for finding patterns in digits, letters, Unicode characters, and string literals. Going forward, you will learn to use zero-length assertions and lookarounds, parsing the source code, and processing the log files. Finally, you will master tips, tricks, and best practices in regex with Java.
Table of Contents (15 chapters)
Title page
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface
Free Chapter
1
Getting Started with Regular Expressions

\G boundary assertion


\G is a zero-width assertion. It is also a boundary matcher that asserts positions at the end of the previous match or at the start of the string, such as the \A assertion for the very first match. The Java regex engine remembers the position of \G within the context of a Matcher instance. If Matcher is instantiated again or is reset, then the position of \G is also initialized to the start of the string.

For example, consider the following input:

,,,,,123,45,67 

Consider that we need to replace every comma that occurs only at the start of the input with a hyphen so that we have the same number of hyphens as the number of commas at the start. Our final output should be the following:

-----123,45,67 

We cannot just do replaceAll by matching each comma, since that will also replace the comma after 123 and 45, and moreover, we want the same number of hyphens as the number of commas in the input string.

For cases like this, we can use the \G assertion and use this Java code snippet...