Home Java javaTutorial Summary of the usage of regular expressions in Java programming

Summary of the usage of regular expressions in Java programming

Jan 20, 2017 am 11:08 AM

This article mainly introduces a summary of the usage of regular expressions in Java programming. Regular expressions are a powerful string processing tool. Java’s support for regular expressions is still very good. Let’s sort out the regular expressions first. Some basic knowledge of expressions:

 1. Regular expressions in strings

Regular expressions can be used to search, extract, split, replace and other operations on strings. The String class provides the following special methods:

boolean matches(String regex): Determine whether the string matches the specified regular expression.

String replaceAll(String regex, String replacement): Replace all substrings matching regex in the string with replacement.

String[] split(String regex): Use regex as the separator to split the string into multiple substrings.

The above special methods all rely on the regular expressions provided by Java.

 2. Create a regular expression

 x: Character x (x can represent any legal character);

 \0mnn: The character represented by the octal number Omnn;

\xhh: The character represented by hexadecimal 0xhh;

\uhhhh: The UNICODE character represented by hexadecimal 0xhhhh;

\t: Tab character ('\u0009');

\n: New line (line feed) character ('\u000A');

\r: Carriage return character ('\u000D');

 \f: Form feed character ('\u000C');

 \a: Alarm (bell) character ('\u0007');

 \e: Escape character ( '\u001B');

 \cx: The control character corresponding to x. For example, \cM matches Ctrl-M. The x value must be one of A~Z or a~z;

 3. Special characters in regular expressions

$: Matches the end of a line. To match the $ character itself, use \$;

 ^: to match the beginning of a line. To match the ^ character itself, use \^;

 (): to mark the beginning and end of a subexpression. To match these characters, use \(and \);

 []: Used to determine the start and end position of the bracket expression. To match these characters, use \[ and \];

 {}: used to mark the frequency of occurrence of the previous subexpression. To match these characters, use \{ and \};

*: Specifies that the preceding subexpression may appear zero or more times. To match the * character itself, use \*;

 +: Specifies that the preceding subexpression can appear one or more times. To match the + character itself, use \+;

 ?: to specify that the preceding subexpression can appear zero or once. To match the ? character itself, use \?;

 .: matches any unit character except the newline character \n. To match the character itself, use \.;

\: used to escape the next character, or specify octal or hexadecimal characters. To match the \ character, use \\;

|: to specify one of the two items. To match the | character itself, use \|;

 4. Predefined characters

 .: Can match any character;

 \d: Match all 0~9 Numbers;

\D: Match non-digits;

\s: Match all whitespace characters, including spaces, tabs, carriage returns, form feeds, line feeds, etc.;

\S: Matches all non-whitespace characters;

\w: Matches all word characters, including all numbers from 0 to 9, 26 English letters and underscores (_);

 \W: Match all non-word characters;

 5. Boundary matching character

 ^: Beginning of line

 $: End of line

 \b: Word boundary

 \B: Non-word boundary

 \A: Beginning of input

 \G: End of previous match

 \Z: The end of the input, only used for the last terminator

 \z: The end of the input

 6. The symbol indicating the number of matches

 The figure shows the symbols representing the number of matches, which are used to determine the number of occurrences of the symbol immediately to the left of the symbol:

Summary of the usage of regular expressions in Java programming

 (1) Suppose we want to in a text file Search for US Social Security numbers. The format of this number is 999-99-9999. The regular expression used to match it is shown in Figure 1. In regular expressions, the hyphen ("-") has a special meaning. It represents a range, such as from 0 to 9. Therefore, when matching a hyphen in a Social Security number, it is preceded by an escape character "\".

 

Summary of the usage of regular expressions in Java programming

 (2) Assume that when searching, you want the hyphen to appear or not appear - that is, 999-99- 9999 and 999999999 are both correct formats. At this time, you can add the "?" quantity limit symbol after the hyphen, as shown in the figure:

Summary of the usage of regular expressions in Java programming


 (3 ) Let’s look at another example below. One format for U.S. car license plates is four numbers plus two letters. Its regular expression is preceded by the numeric part "[0-9]{4}", plus the letter part "[A-Z]{2}". The image below shows the complete regular expression.

Summary of the usage of regular expressions in Java programming

 7.一些实例

  例子1 

function replace(content){
 
 var reg = '\\[(\\w+)\\]',
 
 pattern = new RegExp(reg, 'g');
 
 return content.replace(pattern, '');
 
 }
 
 //或
 
 function replace(content){
 
 return content.replace(/\[(\w+)\/g, '');
 
 }
Copy after login

  例子2  

//zero-width look behind的替换方案
 
  //(?<=...)和(?
  //方法一:反转字符串,用lookahead进行搜索,替换以后再倒回来,例如:
 
  String.prototype.reverse = function () {
 
  return this.split(&#39;&#39;).reverse().join(&#39;&#39;);
 
  }
 
  //模拟&#39;foo.bar|baz&#39;.replace(/(?<=\.)b/, &#39;c&#39;) 即将前面有&#39;.&#39;的b换成c
 
  &#39;foo.bar|baz&#39;.reverse().replace(/b(?=\.)/g, &#39;c&#39;).reverse() //foo.car|baz
 
  //方法二:不用零宽断言,自己判断
 
  //模拟&#39;foo.bar|baz&#39;.replace(/(?<=\.)b/, &#39;c&#39;) 即将前面有&#39;.&#39;的b换成c
 
  &#39;foo.bar|baz&#39;.replace(/(\.)?b/, function ($0, $1) {
 
  return $1 ? $1 + &#39;c&#39; : $0;
 
  }) //foo.car|baz
 
  //模拟&#39;foo.bar|baz&#39;.replace(/(?
  &#39;foo.bar|baz&#39;.replace(/(\.)?b/, function ($0, $1) {
 
  return $1 ? $0 : &#39;c&#39;;
 
  }) //foo.bar|caz
 
  //这个方法在一些比较简单的场景下有用,并且可以和lookahead一起用
 
  //但也有很多场景无效,例如:
 
  //&#39;tttt&#39;.replace(/(?<=t)t/g, &#39;x&#39;) 结果应该是&#39;txxx&#39;
 
  &#39;tttt&#39;.replace(/(t)?t/g, function ($0, $1) {
 
  return $1 ? $1 + &#39;x&#39; : $0;
 
  }) // txtx
Copy after login

 例子3

$&符号的使用
 
 function escapeRegExp(str) {
 
 return str.replace(/[abc]/g, "($&)");
 
 }
 
 var str = &#39;a12b34c&#39;;
 
 console.log(escapeRegExp(str)); //(a)12(b)34(c)
Copy after login

以上就是Java编程中正则表达式的用法总结的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles