Home Backend Development Python Tutorial 详细介绍Ruby中的正则表达式

详细介绍Ruby中的正则表达式

Jun 10, 2016 pm 03:15 PM
ruby

正则表达式是一种特殊序列的字符,它通过使用有专门语法的模式来匹配或查找其他字符串或字符串集合。
语法

正则表达式从字面上看是一种介于斜杠之间或介于跟在 %r 后的任意分隔符之间的模式,如下所示:

/pattern/
/pattern/im  # 可以指定选项
%r!/usr/local! # 一般的分隔的正则表达式
实例
#!/usr/bin/ruby
 
line1 = "Cats are smarter than dogs";
line2 = "Dogs also like meat";
 
if ( line1 =~ /Cats(.*)/ )
 puts "Line1 contains Cats"
end
if ( line2 =~ /Cats(.*)/ )
 puts "Line2 contains Dogs"
end
Copy after login

这将产生以下结果:

Line1 contains Cats
Copy after login

正则表达式修饰符

正则表达式从字面上看可能包含一个可选的修饰符,用于控制各方面的匹配。修饰符在第二个斜杠字符后指定,如上面实例所示。下标列出了 可能的修饰符:

201541093958504.jpg (982×274)

就像字符串通过 %Q 进行分隔一样,Ruby 允许您以 %r 作为正则表达式的开头,后面跟着任意分隔符。这在描述包含大量您不想转义的斜杠字符时非常有用。

# 下面匹配单个斜杠字符,不转义


%r|/|       
 
# Flag 字符可通过下面的语法进行匹配
%r[</(.*)>]i 

Copy after login

正则表达式模式

除了控制字符,(+ ? . * ^ $ ( ) [ ] { } | \),其他所有字符都匹配本身。您可以通过在控制字符前放置一个反斜杠来对控制字符进行转义。

下表列出了 Ruby 中可用的正则表达式语法。

201541094045775.jpg (957×701)

201541094114283.jpg (957×731)201541094152882.jpg (956×720)201541094244206.jpg (951×711)201541094311488.jpg (943×723)201541094334570.jpg (964×279)搜索和替换

sub 和 gsub 及它们的替代变量 sub! 和 gsub! 是使用正则表达式时重要的字符串方法。

所有这些方法都是使用正则表达式模式执行搜索与替换操作。sub 和 sub! 替换模式的第一次出现,gsub 和 gsub! 替换模式的所有出现。

sub 和 gsub 返回一个新的字符串,保持原始的字符串不被修改,而 sub! 和 gsub! 则会修改它们调用的字符串。

下面是一个实例:

#!/usr/bin/ruby
 
phone = "2004-959-559 #This is Phone Number"
 
# 删除 Ruby 的注释
phone = phone.sub!(/#.*$/, "") 
puts "Phone Num : #{phone}"
 
# 移除数字以外的其他字符
phone = phone.gsub!(/\D/, "")  
puts "Phone Num : #{phone}"
Copy after login

这将产生以下结果:

Phone Num : 2004-959-559
Phone Num : 2004959559
Copy after login

下面是另一个实例:

#!/usr/bin/ruby
 
text = "rails are rails, really good Ruby on Rails"
 
# 把所有的 "rails" 改为 "Rails"
text.gsub!("rails", "Rails")
 
# 把所有的单词 "Rails" 都改成首字母大写
text.gsub!(/\brails\b/, "Rails")
 
puts "#{text}"
Copy after login

这将产生以下结果:

Rails are Rails, really good Ruby on Rails
Copy after login

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)

In-depth analysis of the similarities and differences between Golang and Ruby In-depth analysis of the similarities and differences between Golang and Ruby Jun 01, 2024 pm 08:46 PM

The main difference between Go and Ruby is that Go is a statically typed compiled language that supports lightweight parallelism and efficient memory management, and is suitable for writing high-concurrency applications; Ruby is a dynamically typed interpreted language that supports true parallelism but memory management It requires manual control and is suitable for writing flexible web applications.

Why have Python, Ruby and other languages ​​deprecated the increment operator? Why have Python, Ruby and other languages ​​deprecated the increment operator? May 11, 2023 pm 04:37 PM

Many people may notice a phenomenon, that is, in some modern programming languages ​​​​(of course, not referring to "recent" programming languages), the increment and decrement operators have been cancelled. In other words, there is no such expression as i++ or j-- in these languages, but only i+=1 or j-=1 Such an expression. This answer will explore the background and reasons for this phenomenon from the perspective of design philosophy. Strictly speaking, it may be biased to say "i++ is disappearing", because it seems that only Python, Rust and Swift among mainstream programming languages ​​do not support the increment and decrement operators. When I first came into contact with Python, this was also

How does Ruby use Mysql2 connection to operate MySQL? How does Ruby use Mysql2 connection to operate MySQL? Apr 17, 2023 pm 10:07 PM

Ruby operates MySQL using mysql2 to connect to mysql and operate mysql. geminstallmysql2 connects to mysql to establish a connection: require'mysql2'conn=Mysql2::Client.new({host:'192.168.200.73',username:'root',password:'P@ssword1!'}) The accepted connection options include: Mysql2::Clie

How to implement a simple data conversion function using MySQL and Ruby How to implement a simple data conversion function using MySQL and Ruby Sep 21, 2023 am 08:07 AM

How to use MySQL and Ruby to implement a simple data conversion function. In actual development work, data conversion is often required to convert one data format into another data format. This article will introduce how to use MySQL and Ruby to implement a simple data conversion function, and provide specific code examples. First, we need to install and configure the MySQL and Ruby environments. Make sure you have a MySQL database installed and can connect to the database via the command line or other tools. In addition, you need to install

How to implement a simple asynchronous task scheduling function using MySQL and Ruby How to implement a simple asynchronous task scheduling function using MySQL and Ruby Sep 20, 2023 am 10:48 AM

How to use MySQL and Ruby to implement a simple asynchronous task scheduling function. Most of the previous web applications used a synchronous method to process requests, that is, after the user sends a request, the server will immediately process the request and return the result. However, as the complexity of applications increases, the processing efficiency of synchronous methods gradually becomes inefficient, so asynchronous task scheduling has become a common requirement in modern web applications. This article will introduce how to use MySQL and Ruby to implement a simple asynchronous task scheduling function, including task

How to use MySQL and Ruby to implement a simple data analysis report function How to use MySQL and Ruby to implement a simple data analysis report function Sep 20, 2023 pm 05:09 PM

How to use MySQL and Ruby to implement a simple data analysis report function Introduction: In today's data-driven era, data analysis plays a crucial role in corporate decision-making and development. As an important part of data analysis, data analysis reports are of great significance for organizing, visualizing and interpreting data. This article will introduce how to use MySQL and Ruby to implement a simple data analysis report function, and provide corresponding code examples. 1. Database design and table creation must realize data analysis and reporting functions

How to build scalable web applications using Vue.js and Ruby How to build scalable web applications using Vue.js and Ruby Aug 03, 2023 pm 02:27 PM

How to use Vue.js and Ruby language to build scalable web applications. In recent years, with the development and growing needs of web applications, building scalable web applications has become an important topic. As a lightweight JavaScript front-end framework, Vue.js provides a flexible, efficient and scalable solution. At the same time, Ruby, as a concise and easy-to-read programming language, can be used to construct powerful back-end systems. This article will introduce how to combine Vue.js and Ruby language to build

How to use MySQL and Ruby to implement a simple data query and analysis function How to use MySQL and Ruby to implement a simple data query and analysis function Sep 21, 2023 pm 04:36 PM

How to use MySQL and Ruby to implement a simple data query and analysis function. In today's big data era, data analysis has become an indispensable part in many fields. When performing data analysis, the most common operation is data query. This article will introduce how to use MySQL and Ruby programming language to implement a simple data query and analysis function, and give specific code examples. First, we need to install the MySQL and Ruby development environments. MySQL is an open source relational database

See all articles