Home Web Front-end JS Tutorial Detailed explanation of the steps to obtain regular expressions using regular expression objects

Detailed explanation of the steps to obtain regular expressions using regular expression objects

May 25, 2018 am 10:03 AM
accomplish object expression

这次给大家带来使用正则表达式对象实现正则获取步骤详解,使用正则表达式对象实现正则获取的注意事项有哪些,下面就是实战案例,一起来看一下。

获取需要使用到正则的两个对象:

使用的是用正则对象Pattern 和匹配器Matcher。

用法:

范例:

 Pattern p = Pattern.compile("a*b");
 Matcher m = p.matcher("aaaaab");
 boolean b = m.matches();
Copy after login

步骤:

1,先将正则表达式编译成正则对象。使用的是Pattern类一个静态的方法。compile(regex);

2,让正则对象和要操作的字符串相关联,通过matcher方法完成,并返回匹配器对象。

3,通过匹配器对象的方法将正则模式作用到字符串上对字符串进行针对性的功能操作

需求:获取由3个字母组成的单词。

public static void getDemo()
{
  String str = "da jia zhu yi le,ming tian bu fang jia,xie xie!";
  //想要获取由3个字母组成的单词。
  //刚才的功能返回的都是一个结果,只有split返回的是数组,但是它是把规则作为分隔符,不会获取符合规则的内容。
  //这时我们要用到一些正则对象。
  String reg = "\\b[a-z]{3}\\b";
  Pattern p = Pattern.compile(reg);
  Matcher m = p.matcher(str);
  while(m.find())
  {
    System.out.println(m.start()+"...."+m.end());
    System.out.println("sub:"+str.substring(m.start(),m.end()));
    System.out.println(m.group());
  }
//   System.out.println(m.find());//将规则对字符串进行匹配查找。
//   System.out.println(m.find());//将规则对字符串进行匹配查找。
//   System.out.println(m.group());//在使用group方法之前,必须要先找,找到了才可以取。
}
Copy after login

校验邮件

public static void checkMail()
{
  String mail = "abc123@sina.com.cn";
  mail = "1@1.1";
  String reg = "[a-zA-Z_0-9]+@[a-zA-Z0-9]+(\\.[a-zA-Z]+)+";
  reg = "\\w+@\\w+(\\.\\w+)+";//简化的规则。笼统的匹配。
  boolean b = mail.matches(reg);
  System.out.println(mail+":"+b);
}
Copy after login

网络爬虫 (获取邮箱)

class GetMailList 
{
public static void main(String[] args) throws Exception
{
  String reg = "\\w+@[a-zA-Z]+(\\.[a-zA-Z]+)+";
  getMailsByWeb(reg);
}
public static void getMailsByWeb(String regex)throws Exception
{
  URL url = new URL("http://localhost:8080/myweb/mail.html");
  URLConnection conn = url.openConnection();
  BufferedReader bufIn = new BufferedReader(new InputStreamReader(conn.getInputStream()));
  String line = null;
  Pattern p = Pattern.compile(regex);   
  while((line=bufIn.readLine())!=null)
  {
    //System.out.println(line);
    Matcher m = p.matcher(line);
    while(m.find())
    {
      System.out.println(m.group());
    }
  }
  bufIn.close();
}
public static void getMails(String regex)throws Exception
{
  BufferedReader bufr = 
    new BufferedReader(new FileReader("mail.txt"));
  String line = null;
  Pattern p = Pattern.compile(regex);   
  while((line=bufr.readLine())!=null)
  {
    //System.out.println(line);
    Matcher m = p.matcher(line);
    while(m.find())
    {
      System.out.println(m.group());
    }
  }
  bufr.close();
}
}
Copy after login

单词边界匹配器 \b

\b代表一个单词的开始和结束部分,不匹配任何字符

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

使用前端方法实现图片转字符画

JS数组方法使用步骤详解

The above is the detailed content of Detailed explanation of the steps to obtain regular expressions using regular expression objects. 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)

How to implement dual WeChat login on Huawei mobile phones? How to implement dual WeChat login on Huawei mobile phones? Mar 24, 2024 am 11:27 AM

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

PHP Programming Guide: Methods to Implement Fibonacci Sequence PHP Programming Guide: Methods to Implement Fibonacci Sequence Mar 20, 2024 pm 04:54 PM

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

How to implement the WeChat clone function on Huawei mobile phones How to implement the WeChat clone function on Huawei mobile phones Mar 24, 2024 pm 06:03 PM

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

Master how Golang enables game development possibilities Master how Golang enables game development possibilities Mar 16, 2024 pm 12:57 PM

In today's software development field, Golang (Go language), as an efficient, concise and highly concurrency programming language, is increasingly favored by developers. Its rich standard library and efficient concurrency features make it a high-profile choice in the field of game development. This article will explore how to use Golang for game development and demonstrate its powerful possibilities through specific code examples. 1. Golang’s advantages in game development. As a statically typed language, Golang is used in building large-scale game systems.

PHP Game Requirements Implementation Guide PHP Game Requirements Implementation Guide Mar 11, 2024 am 08:45 AM

PHP Game Requirements Implementation Guide With the popularity and development of the Internet, the web game market is becoming more and more popular. Many developers hope to use the PHP language to develop their own web games, and implementing game requirements is a key step. This article will introduce how to use PHP language to implement common game requirements and provide specific code examples. 1. Create game characters In web games, game characters are a very important element. We need to define the attributes of the game character, such as name, level, experience value, etc., and provide methods to operate these

How to convert MySQL query result array to object? How to convert MySQL query result array to object? Apr 29, 2024 pm 01:09 PM

Here's how to convert a MySQL query result array into an object: Create an empty object array. Loop through the resulting array and create a new object for each row. Use a foreach loop to assign the key-value pairs of each row to the corresponding properties of the new object. Adds a new object to the object array. Close the database connection.

How do PHP functions return objects? How do PHP functions return objects? Apr 10, 2024 pm 03:18 PM

PHP functions can encapsulate data into a custom structure by returning an object using a return statement followed by an object instance. Syntax: functionget_object():object{}. This allows creating objects with custom properties and methods and processing data in the form of objects.

What is the difference between arrays and objects in PHP? What is the difference between arrays and objects in PHP? Apr 29, 2024 pm 02:39 PM

In PHP, an array is an ordered sequence, and elements are accessed by index; an object is an entity with properties and methods, created through the new keyword. Array access is via index, object access is via properties/methods. Array values ​​are passed and object references are passed.

See all articles