当前位置:网站首页>Getting to know regular expressions
Getting to know regular expressions
2022-07-31 05:47:00 【Tahiti0325】
when trying to solve a problem,浏览器搜索How to get only numbers or only letters in a string时,Just happened to see regular expressions.
当然了,Uses of regular expressions include, but are not limited to.
题目如下:
我的代码如下:
package chapter7;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class q7_17 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input=new Scanner(System.in);
System.out.print("请输入学生人数:");
int n;
int i,j,k;
String temp="";
int size=1000;
n=input.nextInt();
System.out.println("请输入学生姓名和成绩:");
String[] nasc=new String[size];//姓名&分数
String str="";
String[] name=new String[size];//姓名
String[] score=new String[size];//分数
for(i=0;i<=n;i++) {
nasc[i]=input.nextLine();
str=String.valueOf(nasc[i]);
String regCa="[^A-z]"; //Regularly looking for names(英文)
Pattern p = Pattern.compile(regCa);
Matcher x = p.matcher(str);
name[i]=x.replaceAll("").trim();
String regEx="[^0-9]"; //Regularly find numbers
Pattern q = Pattern.compile(regEx);
Matcher y = q.matcher(str);
score[i]=y.replaceAll("").trim();
}
for(j=1;j<i;j++) {
boolean flag=true;
for(k=1;k<i-j;k++) {
int a=Integer.parseInt(score[k]);
int b=Integer.parseInt(score[k+1]);
if(a<b) {
temp=score[k];
score[k]=score[k+1];
score[k+1]=temp;
temp=name[k];
name[k]=name[k+1];
name[k+1]=temp;
flag=false;
}
}
if(flag) {
break;
}
}
for(int l=0;l<i;l++) {
System.out.println(name[l]);
}
input.close();
}
}
正则表达式(regular expression)是一个用于匹配字符串的模板.Any string can be treated as a regular expression.例如,“Java”就是一个正则表达式,But it can only match strings“Java”,Cannot match other strings.
Usually regular expressions can match a batch of strings.
Regular expressions consist of ordinary characters and special characters.
常用的正则表达式:
以下内容引自wikipedia:
POSIX basic and extended
正则表达式的元字符:
Metacharacter | Description |
---|---|
^ | Matches the starting position within the string. In line-based tools, it matches the starting position of any line. |
. | Matches any single character (many applications exclude newlines, and exactly which characters are considered newlines is flavor-, character-encoding-, and platform-specific, but it is safe to assume that the line feed character is included). Within POSIX bracket expressions, the dot character matches a literal dot. For example, a.c matches "abc", etc., but [a.c] matches only "a", ".", or "c". |
[ ] | A bracket expression. Matches a single character that is contained within the brackets. For example, [abc] matches "a", "b", or "c". [a-z] specifies a range which matches any lowercase letter from "a" to "z". These forms can be mixed: [abcx-z] matches "a", "b", "c", "x", "y", or "z", as does [a-cx-z] . The |
[^ ] | Matches a single character that is not contained within the brackets. For example, [^abc] matches any character other than "a", "b", or "c". [^a-z] matches any single character that is not a lowercase letter from "a" to "z". Likewise, literal characters and ranges can be mixed. |
$ | Matches the ending position of the string or the position just before a string-ending newline. In line-based tools, it matches the ending position of any line. |
( ) | Defines a marked subexpression. The string matched within the parentheses can be recalled later (see the next entry, \n ). A marked subexpression is also called a block or capturing group. BRE mode requires \( \) . |
\n | Matches what the nth marked subexpression matched, where n is a digit from 1 to 9. This construct is vaguely defined in the POSIX.2 standard. Some tools allow referencing more than nine capturing groups. Also known as a backreference. |
* | Matches the preceding element zero or more times. For example, ab*c matches "ac", "abc", "abbbc", etc. [xyz]* matches "", "x", "y", "z", "zx", "zyx", "xyzzy", and so on. (ab)* matches "", "ab", "abab", "ababab", and so on. |
{ m,n} | Matches the preceding element at least m and not more than n times. For example, a{3,5} matches only "aaa", "aaaa", and "aaaaa". This is not found in a few older instances of regexes. BRE mode requires \{ m,n\} . |
Examples:
.at
matches any three-character string ending with "at", including "hat", "cat", and "bat".[hc]at
matches "hat" and "cat".[^b]at
matches all strings matched by.at
except "bat".[^hc]at
matches all strings matched by.at
other than "hat" and "cat".^[hc]at
matches "hat" and "cat", but only at the beginning of the string or line.[hc]at$
matches "hat" and "cat", but only at the end of the string or line.\[.\]
matches any single character surrounded by "[" and "]" since the brackets are escaped, for example: "[a]" and "[b]".s.*
matches s followed by zero or more characters, for example: "s" and "saw" and "seed".
POSIX extended[edit]
The meaning of metacharacters escaped with a backslash is reversed for some characters in the POSIX Extended Regular Expression (ERE) syntax. With this syntax, a backslash causes the metacharacter to be treated as a literal character. So, for example, \( \)
is now ( )
and \{ \}
is now { }
. Additionally, support is removed for \n
backreferences and the following metacharacters are added:
Metacharacter | Description |
---|---|
? | Matches the preceding element zero or one time. For example, ab?c matches only "ac" or "abc". |
+ | Matches the preceding element one or more times. For example, ab+c matches "abc", "abbc", "abbbc", and so on, but not "ac". |
| | The choice (also known as alternation or set union) operator matches either the expression before or the expression after the operator. For example, abc|def matches "abc" or "def". |
Examples:
[hc]?at
matches "at", "hat", and "cat".[hc]*at
matches "at", "hat", "cat", "hhat", "chat", "hcat", "cchchat", and so on.[hc]+at
matches "hat", "cat", "hhat", "chat", "hcat", "cchchat", and so on, but not "at".cat|dog
matches "cat" or "dog".
POSIX Extended Regular Expressions can often be used with modern Unix utilities by including the command line flag -E.
Character classes[edit]
The character class is the most basic regex concept after a literal match. It makes one small sequence of characters match a larger set of characters. For example, [A-Z]
could stand for any uppercase letter in the English alphabet, and \d
could mean any digit. Character classes apply to both POSIX levels.
When specifying a range of characters, such as [a-Z]
(i.e. lowercase a
to uppercase Z
), the computer's locale settings determine the contents by the numeric ordering of the character encoding. They could store digits in that sequence, or the ordering could be abc…zABC…Z, or aAbBcC…zZ. So the POSIX standard defines a character class, which will be known by the regex processor installed. Those definitions are in the following table:
Predefined character classes for regular expressions:
POSIX | Non-standard | Perl/Tcl | Vim | Java | ASCII | Description |
---|---|---|---|---|---|---|
[:ascii:] [31] | \p{ASCII} | [\x00-\x7F] | ASCII characters | |||
[:alnum:] | \p{Alnum} | [A-Za-z0-9] | Alphanumeric characters | |||
[:word:] [31] | \w | \w | \w | [A-Za-z0-9_] | Alphanumeric characters plus "_" | |
\W | \W | \W | [^A-Za-z0-9_] | Non-word characters | ||
[:alpha:] | \a | \p{Alpha} | [A-Za-z] | Alphabetic characters | ||
[:blank:] | \s | \p{Blank} | [ \t] | Space and tab | ||
\b | \< \> | \b | (?<=\W)(?=\w)|(?<=\w)(?=\W) | Word boundaries | ||
\B | (?<=\W)(?=\W)|(?<=\w)(?=\w) | Non-word boundaries | ||||
[:cntrl:] | \p{Cntrl} | [\x00-\x1F\x7F] | Control characters | |||
[:digit:] | \d | \d | \p{Digit} or \d | [0-9] | Digits | |
\D | \D | \D | [^0-9] | Non-digits | ||
[:graph:] | \p{Graph} | [\x21-\x7E] | Visible characters | |||
[:lower:] | \l | \p{Lower} | [a-z] | Lowercase letters | ||
[:print:] | \p | \p{Print} | [\x20-\x7E] | Visible characters and the space character | ||
[:punct:] | \p{Punct} | [][!"#$%&'()*+,./:;<=>[email protected]\^_`{|}~-] | Punctuation characters | |||
[:space:] | \s | \_s | \p{Space} or \s | [ \t\r\n\v\f] | Whitespace characters | |
\S | \S | \S | [^ \t\r\n\v\f] | Non-whitespace characters | ||
[:upper:] | \u | \p{Upper} | [A-Z] | Uppercase letters | ||
[:xdigit:] | \x | \p{XDigit} | [A-Fa-f0-9] | Hexadecimal digits |
正则表达式的元字符+预定义字符类用例:
Metacharacter(s) | Description | Example[51] |
---|---|---|
. | Normally matches any character except a newline. Within square brackets the dot is literal. | $string1 = "Hello World\n"; if ($string1 =~ m/...../) { print "$string1 has length >= 5.\n"; } Output: Hello World has length >= 5. |
( ) | Groups a series of pattern elements to a single element. When you match a pattern within parentheses, you can use any of $1 , $2 , ... later to refer to the previously matched pattern. | $string1 = "Hello World\n"; if ($string1 =~ m/(H..).(o..)/) { print "We matched '$1' and '$2'.\n"; } Output: We matched 'Hel' and 'o W'. |
+ | Matches the preceding pattern element one or more times. | $string1 = "Hello World\n"; if ($string1 =~ m/l+/) { print "There are one or more consecutive letter \"l\"'s in $string1.\n"; } Output: There are one or more consecutive letter "l"'s in Hello World. |
? | Matches the preceding pattern element zero or one time. | $string1 = "Hello World\n"; if ($string1 =~ m/H.?e/) { print "There is an 'H' and a 'e' separated by "; print "0-1 characters (e.g., He Hue Hee).\n"; } Output: There is an 'H' and a 'e' separated by 0-1 characters (e.g., He Hue Hee). |
? | Modifies the * , + , ? or {M,N} 'd regex that comes before to match as few times as possible. | $string1 = "Hello World\n"; if ($string1 =~ m/(l.+?o)/) { print "The non-greedy match with 'l' followed by one or "; print "more characters is 'llo' rather than 'llo Wo'.\n"; } Output: The non-greedy match with 'l' followed by one or more characters is 'llo' rather than 'llo Wo'. |
* | Matches the preceding pattern element zero or more times. | $string1 = "Hello World\n"; if ($string1 =~ m/el*o/) { print "There is an 'e' followed by zero to many "; print "'l' followed by 'o' (e.g., eo, elo, ello, elllo).\n"; } Output: There is an 'e' followed by zero to many 'l' followed by 'o' (e.g., eo, elo, ello, elllo). |
{M,N} | Denotes the minimum M and the maximum N match count. N can be omitted and M can be 0: {M} matches "exactly" M times; {M,} matches "at least" M times; {0,N} matches "at most" N times.x* y+ z? is thus equivalent to x{0,} y{1,} z{0,1} . | $string1 = "Hello World\n"; if ($string1 =~ m/l{1,2}/) { print "There exists a substring with at least 1 "; print "and at most 2 l's in $string1\n"; } Output: There exists a substring with at least 1 and at most 2 l's in Hello World |
[…] | Denotes a set of possible character matches. | $string1 = "Hello World\n"; if ($string1 =~ m/[aeiou]+/) { print "$string1 contains one or more vowels.\n"; } Output: Hello World contains one or more vowels. |
| | Separates alternate possibilities. | $string1 = "Hello World\n"; if ($string1 =~ m/(Hello|Hi|Pogo)/) { print "$string1 contains at least one of Hello, Hi, or Pogo."; } Output: Hello World contains at least one of Hello, Hi, or Pogo. |
\b | Matches a zero-width boundary between a word-class character (see next) and either a non-word class character or an edge; same as
| $string1 = "Hello World\n"; if ($string1 =~ m/llo\b/) { print "There is a word that ends with 'llo'.\n"; } Output: There is a word that ends with 'llo'. |
\w | Matches an alphanumeric character, including "_"; same as [A-Za-z0-9_] in ASCII, and
in Unicode,[47] where the | $string1 = "Hello World\n"; if ($string1 =~ m/\w/) { print "There is at least one alphanumeric "; print "character in $string1 (A-Z, a-z, 0-9, _).\n"; } Output: There is at least one alphanumeric character in Hello World (A-Z, a-z, 0-9, _). |
\W | Matches a non-alphanumeric character, excluding "_"; same as [^A-Za-z0-9_] in ASCII, and
in Unicode. | $string1 = "Hello World\n"; if ($string1 =~ m/\W/) { print "The space between Hello and "; print "World is not alphanumeric.\n"; } Output: The space between Hello and World is not alphanumeric. |
\s | Matches a whitespace character, which in ASCII are tab, line feed, form feed, carriage return, and space; in Unicode, also matches no-break spaces, next line, and the variable-width spaces (amongst others). | $string1 = "Hello World\n"; if ($string1 =~ m/\s.*\s/) { print "In $string1 there are TWO whitespace characters, which may"; print " be separated by other characters.\n"; } Output: In Hello World there are TWO whitespace characters, which may be separated by other characters. |
\S | Matches anything but a whitespace. | $string1 = "Hello World\n"; if ($string1 =~ m/\S.*\S/) { print "In $string1 there are TWO non-whitespace characters, which"; print " may be separated by other characters.\n"; } Output: In Hello World there are TWO non-whitespace characters, which may be separated by other characters. |
\d | Matches a digit; same as [0-9] in ASCII;in Unicode, same as the \p{Digit} or \p{GC=Decimal_Number} property, which itself the same as the \p{Numeric_Type=Decimal} property. | $string1 = "99 bottles of beer on the wall."; if ($string1 =~ m/(\d+)/) { print "$1 is the first number in '$string1'\n"; } Output: 99 is the first number in '99 bottles of beer on the wall.' |
\D | Matches a non-digit; same as [^0-9] in ASCII or \P{Digit} in Unicode. | $string1 = "Hello World\n"; if ($string1 =~ m/\D/) { print "There is at least one character in $string1"; print " that is not a digit.\n"; } Output: There is at least one character in Hello World that is not a digit. |
^ | Matches the beginning of a line or string. | $string1 = "Hello World\n"; if ($string1 =~ m/^He/) { print "$string1 starts with the characters 'He'.\n"; } Output: Hello World starts with the characters 'He'. |
$ | Matches the end of a line or string. | $string1 = "Hello World\n"; if ($string1 =~ m/rld$/) { print "$string1 is a line or string "; print "that ends with 'rld'.\n"; } Output: Hello World is a line or string that ends with 'rld'. |
\A | Matches the beginning of a string (but not an internal line). | $string1 = "Hello\nWorld\n"; if ($string1 =~ m/\AH/) { print "$string1 is a string "; print "that starts with 'H'.\n"; } Output: Hello World is a string that starts with 'H'. |
\z | Matches the end of a string (but not an internal line).[52] | $string1 = "Hello\nWorld\n"; if ($string1 =~ m/d\n\z/) { print "$string1 is a string "; print "that ends with 'd\\n'.\n"; } Output: Hello World is a string that ends with 'd\n'. |
[^…] | Matches every character except the ones inside brackets. | $string1 = "Hello World\n"; if ($string1 =~ m/[^abc]/) { print "$string1 contains a character other than "; print "a, b, and c.\n"; } Output: Hello World contains a character other than a, b, and c. |
边栏推荐
- 常见JVM面试题及答案整理
- The process and specific code of sending SMS verification code using flask framework
- leetcode-每日一题735. 行星碰撞(栈模拟)
- Redis:简单实用
- Oracle数据库中的“limit”查询
- gin框架学习-Casbin进阶之策略管理API使用方法
- Anaconda configure environment directives
- Error: Cannot find module ‘D:\Application\nodejs\node_modules\npm\bin\npm-cli.js‘
- 04 【计算属性 侦听属性】
- 【windows】--- SQL Server 2008 超详细安装教程
猜你喜欢
随机推荐
GUCCI, LV and other luxury giant universe how to layout yuan, other brands should keep up with?
数据库上机实验7 数据库设计
wpf ScrowViewer水平滚动
数据库上机实验6 数据库完整性
04 【计算属性 侦听属性】
sqlmap注入教程 常用指令
可以“繁殖”的程序
gin框架学习-Casbin入门指南(ACL、RBAC、域内RBAC模型)
feign调用不通问题,JSON parse error Illegal character ((CTRL-CHAR, code 31)) only regular white space (r
数据库上机实验5 数据库安全性
【uiautomation】微信好友列表获取(存储到txt中)
uni-app进阶之内嵌应用【day14】
16 【打包上线 图片懒加载】
【Elastic-Job】分布式调度任务概览篇
【Elastic-Job源码分析】——作业监听器
继承、Super,重写、抽象类、抽象方法 1(第七天)
uni-app进阶之创建组件/原生渲染【day9】
Access数据库的查询
什么是EVM兼容链?
vulhub靶场学习日记hackme1