Home Web Front-end JS Tutorial Position matching tutorial for regular expression tutorial (with code)

Position matching tutorial for regular expression tutorial (with code)

Mar 29, 2018 pm 06:03 PM
Location match expression

This time I bring you the position matching tutorial of the regular expression tutorial (with code), what are the precautions for using the regular expression tutorial position matching, the following is the actual combat Let’s take a look at the case.

The example in this article describes the positional matching of regular expression tutorial. Share it with everyone for your reference, as follows:

Note: In all examples, the regular expression matching results contain [ and ]## in the source text. #, some examples will be implemented using Java. If it is the usage of regular expressions in Java itself, it will be explained in the corresponding place. All java examples are tested under JDK1.6.0_13.

1. Introduction to the problem

If we want to match a certain word in a text (not considering the multi-line mode for now, which will be introduced later), we It might look like this:

Text:

Yesterday is history, tomorrow is a mystery, but today is a gift.

Regular expression:

is

Result:

Yesterday 【is】 h【is】tory, tomorrow 【is】 a mystery, but today 【is】 a gift.

Analysis: Originally it only wanted to match the word is, but it also matched the is contained in other words. To solve this problem, use boundary delimiters, that is, use some

metacharacters in the regular expression to indicate where (or boundary) we want the matching operation to occur.

2. Word Boundary

A commonly used boundary is the word boundary specified by the qualifier \b, which is used to match the beginning and end of a word. More precisely, it matches a position between a character that can be used to form a word (letter, number, underscore, which is the character matched by \w) and a character that cannot be used to form a word ( characters that match \W). Let’s look at the previous example:

Text:

Yesterday is history, tomorrow is a mystery, but today is a gift.

Regular expression:

\bis \b

Result:

Yesterday 【is】 history, tomorrow 【is】 a mystery, but today 【is】 a gift.

Analysis: In the original text, there is a space before and after the word is, and this matches the pattern \bis\b (space is one of the characters used to separate words) . The word history also contains is, because there are two characters h and t before and after it. Neither of these two characters can match \b.

If a word boundary is not matched, \B is used. For example:

Text:

Please enter the nine-digit id as it appears on your color - coded pass-key.

Regular expression:

\B -\B

Result:

Please enter the 【nine-digit】 id as it appears on your color - coded 【pass-key】 .

Analysis: \B-\B will match a hyphen that is not a word boundary before and after. There are no spaces before and after the hyphen in nine-digit and pass-key, so they can match, and color - There are spaces before and after the hyphen in coded, so it cannot be matched.

3. StringBoundary

Word boundary can be used to match positions related to words (beginning of word, end of word, entire word, etc. wait). String boundaries have a similar purpose, but are used to match positions related to strings (beginning of string, end of string, entire string, etc.). There are two metacharacters used to define string boundaries: one is ^ used to define the beginning of the string, and the other is $ used to define the end of the string.

For example, if you want to check the legality of an XML document, legal XML documents begin with :

Text:

<?xml version="1.0" encoding="UTF-8"?>
<project basedir="." default="ear">
</project>
Copy after login

正则表达式:^\s*<\?xml.*?\?>

结果:



分析:^匹配一个字符串的开头位置,所以^\s*将匹配一个字符串的开头位置和随后的零个或多个空白字符,因为标签前面允许有空格、制表符、换行符等空白字符。

$元字符符的用法除了位置上的差异外,与^用法完全一样。比如,检查一个html页面是否以结尾,可以用模式:\s*$

四、多行匹配模式

正则表达式可以通过一些特殊的元字符来改变另外一些元字符的行为。可以通过(?m) 来启用多行匹配模式。多行匹配模式将使得正则表达式引擎把行分隔符当做一个字符串分隔符来对待。在多行匹配模式下,^不仅匹配正常的字符串开头,还将匹配行分隔符(换行符)后面的开始位置,$不仅匹配正常的字符串结尾,还将匹配行分隔符(换行符)后面的结束位置。

在使用时,(?m)必须出现在整个模式的最前面。比如,通过正则表达式把一段java代码中的单行注释(以//开始)内容全部找出来。

文本:

publicDownloadingDialog(Frame parent){
     //Callsuper constructor, specifying that dialog box is modal.
     super(parent,true);
     //Setdialog box title.
     setTitle("E-mailClient");
     //Instructwindow not to close when the "X" is clicked.
     setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
     //Puta message with a nice border in this dialog box.
     JPanelcontentPanel = new JPanel();
     contentPanel.setBorder(BorderFactory.createEmptyBorder(5,5, 5, 5));
     contentPanel.add(newJLabel("Downloading messages..."));
     setContentPane(contentPanel);
     //Sizedialog box to components.
     pack();
     //Centerdialog box over application.
     setLocationRelativeTo(parent);
}
Copy after login

正则表达式:(?m)^\s*//.*$

结果:

         publicDownloadingDialog(Frame parent){
【              //Call superconstructor, specifying that dialog box is modal.】                   super(parent,true);
【              //Set dialog boxtitle.】                   setTitle("E-mailClient");
【              //Instruct windownot to close when the "X" is clicked.】                   setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
【              //Put a messagewith a nice border in this dialog box.】                   JPanelcontentPanel = new JPanel();
                   contentPanel.setBorder(BorderFactory.createEmptyBorder(5,5, 5, 5));
                   contentPanel.add(newJLabel("Downloading messages..."));
                   setContentPane(contentPanel);
【              //Size dialog boxto components.】                   pack();
【              //Center dialogbox over application.】                   setLocationRelativeTo(parent);
         }

分析:^\s*//.*$将匹配一个字符串的开始,然后是任意多个空白字符,再后面是//,再往后是任意文本,最后是一个字符串的结束。不过这个模式只能找出第一条注释,加上(?m)前缀后,将把换行符视为一个字符串分隔符,这样就可以把每一行注释匹配出来了。

java代码实现如下(文本保存在text.txt文件中):

public static String getTextFromFile(String path) throws Exception{
  BufferedReader br = new BufferedReader(new FileReader(new File(path)));
  StringBuilder sb = new StringBuilder();
  char[] cbuf = new char[1024];
  int len = 0;
  while(br.ready() && (len = br.read(cbuf)) > 0){
    br.read(cbuf);
    sb.append(cbuf, 0, len);
  }
    br.close();
  return sb.toString();
}
public static void multilineMatch() throws Exception{
  String text = getTextFromFile("E:/text.txt");
  String regex = "(?m)^\\s*//.*$";
  Matcher m = Pattern.compile(regex).matcher(text);
  while(m.find()){
    System.out.println(m.group());
  }
}
Copy after login

输出结果如下:

//Call super constructor, specifying that dialog box is modal.
//Set dialog box title.
//Instruct window not to close when the "X" is clicked.
//Put a message with a nice border in this dialog box.
//Size dialog box to components.
//Center dialog box over application.

5. Summary

Regular expressions can not only be used to match text blocks of any length, but can also be used to match text that appears at specific positions in a string. \b is used to specify a word boundary (\B is just the opposite). ^ and $ are used to specify word boundaries. If used with (?m), ^ and $ will also match strings that begin or end with a newline character. The use of subexpressions will be introduced in the next article.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to match consecutive numbers with regular expressions

##Development experience of implementing minimum matching with regular expressions

The above is the detailed content of Position matching tutorial for regular expression tutorial (with code). For more information, please follow other related articles on the PHP Chinese website!

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)

Details on how to turn on environment variable settings on Windows 11 Details on how to turn on environment variable settings on Windows 11 Dec 30, 2023 pm 06:07 PM

The environment variable function is an essential tool for running the configuration program in the system. However, in the latest win11 system, there are still many users who do not know how to set it up. Here is a detailed introduction to the location of the win11 environment variable opening. Come and join us. Learn to operate it. Where are the win11 environment variables: 1. First enter "win+R" to open the run box. 2. Then enter the command: controlsystem. 3. In the system information interface that opens, select "Advanced System Settings" from the left menu. 4. Then select the "Environment Variables" option at the bottom of the "System Properties" window that opens. 5. Finally, in the opened environment variables, you can make relevant settings according to your needs.

Win11 startup path and how to open it Win11 startup path and how to open it Jan 03, 2024 pm 11:13 PM

Every Windows system has a startup path. If you add files or software to it, it will be opened at boot time. However, many friends don’t know where the win11 startup path is. In fact, we only need to enter the corresponding folder on the C drive. Win11 startup path: 1. Double-click to open "This PC" 2. Directly paste the path "C:\ProgramData\Microsoft\Windows\StartMenu\Programs\Startup" into the path box. 3. Here is the win11 startup path. If we want to open the file after booting, we can put the file in. 4. If you cannot enter according to this path, it may be hidden.

where is windows10 credential manager where is windows10 credential manager Jul 09, 2023 am 10:09 AM

The Credential Manager is a function used by users to manage web credentials and Windows credentials, but many users still don’t know where the Windows 10 Credential Manager is. In fact, the credential manager is on the operation panel. After opening the control panel, remember to change the viewing method to a small icon, so that you can see the credential manager. Click View to view all kinds of information. If you want to view a large amount of , you need to enter the account password. Where is the Windows 10 Credential Manager: 1. Open the Control Panel in the system, click the View method in the upper right corner, and convert the type to a small icon. 2. After viewing it as a small icon, click "Certificate Manager". 3. After entering the credential manager, you can see an introduction to the relevant functions, which are mainly used for

Location of Origami Bird at Stardome Railway Crocker Film and Television Park Location of Origami Bird at Stardome Railway Crocker Film and Television Park Mar 27, 2024 pm 11:51 PM

There are a total of 20 origami birds in Croaker Film and Television Park on Star Dome Railway. Many players don’t know where the origami birds are in Crocker Film and Television Park. The editor has summarized the locations of each origami bird to help everyone. Search for it, and take a look at this latest summary of the locations of the origami birds in Croaker Film and Television Park for specific content. Guide to the Honkai Star Dome Railway: Origami Bird in Crook Movie Park Location 1, Crook Movie Park 1st Floor 2, and Crook Movie Park 2nd Floor Star Dome Railway

Understand the location and structure of pip installation package storage Understand the location and structure of pip installation package storage Jan 18, 2024 am 08:23 AM

To learn more about the storage location of packages installed by pip, you need specific code examples. Pip is a commonly used package management tool in the Python language. It is used to easily install, upgrade and manage Python packages. When using pip to install a package, it will automatically download the corresponding package file from PyPI (Python Package Index) and install it to the specified location. So, where are the packages installed by pip stored? This is a problem that many Python developers will encounter. This article will delve into the location of the packages installed by pip and provide

Practical Guide to Regular Expressions in Go: How to Match Hexadecimal Color Codes Practical Guide to Regular Expressions in Go: How to Match Hexadecimal Color Codes Jul 13, 2023 am 10:46 AM

Go Language Regular Expressions Practical Guide: How to Match Hexadecimal Color Codes Introduction: Regular expressions are a powerful and flexible tool for pattern matching and finding strings. In Go language, we can use the built-in regular expression package regexp to implement these operations. This article will introduce how to use regular expressions to match hexadecimal color codes in Go language. Importing the regular expression package First, we need to import the regular expression package regexp of the Go language. You can add the following import statement at the beginning of the code: i

win11 shutdown location win11 shutdown location Jan 10, 2024 am 09:14 AM

If we are going to be away from the computer for a long time, it is best to shut down the computer to protect it. So where is the shutdown in win11? In fact, generally speaking, just open the start menu and you can find the shutdown button in it. Where to shut down Windows 11: Answer: In the power button of the start menu. 1. First, we click the "Windows Logo" on the bottom taskbar to open the "Start Menu" 2. After opening, you can find the "Power" button in the lower right corner, as shown in the figure. 3. After clicking the power button, you will see "Shutdown", click it to shut down. 4. If the computer cannot be shut down due to special circumstances such as a crash, you can directly press and hold the "power button" on the computer to force a shutdown.

Using Apple's Check-In Feature: A Guide to the Messages App in iOS 17 Using Apple's Check-In Feature: A Guide to the Messages App in iOS 17 Sep 14, 2023 pm 09:13 PM

Apple in iOS 17 has added a new feature in Messages to let loved ones know when you're home safely. It's called check-in, and here's how you use it. Whether you're walking home after dark or going for an early morning run, you can start checking in with family or friends in Apple's Messages app to let them know when you're home safely. Upon your arrival, CheckIn automatically detects when you are home and notifies your friends. When they are alerted and the check-in has ended, you will also be notified. If something unexpected happens and you're delayed en route, CheckTab will even recognize that you're not making progress and check in with you, asking if you want to increase your ETA. if you don't have

See all articles