初识正则表达式

在试图解决一道题的时候,浏览器搜索怎么在字符串中仅获取数字或仅获取字母时,恰好看到了正则表达式。

当然了,正则表达式的用处包括但不限于此。

题目如下:

我的代码如下:

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]";  //正则找名字(英文)
        	Pattern p = Pattern.compile(regCa);  
        	Matcher x = p.matcher(str);  
        	name[i]=x.replaceAll("").trim();  
        	String regEx="[^0-9]";  //正则找数字
        	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)是一个用于匹配字符串的模板。任何字符串都可以视为正则表达式。例如,“Java”就是一个正则表达式,但它只能匹配字符串“Java”,不能匹配其他字符串。

通常正则表达式能够匹配一批字符串。

正则表达式由普通字符和特殊字符构成。

     

常用的正则表达式:

以下内容引自wikipedia:

POSIX basic and extended

正则表达式的元字符:

MetacharacterDescription
^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 - character is treated as a literal character if it is the last or the first (after the ^, if present) character within the brackets: [abc-][-abc]. Note that backslash escapes are not allowed. The ] character can be included in a bracket expression if it is the first (after the ^) character: []abc].

[^ ]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 \( \).
\nMatches 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:

MetacharacterDescription
?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:

正则表达式的预定义字符类:

POSIXNon-standardPerl/TclVimJavaASCIIDescription
[: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}[][!"#$%&'()*+,./:;<=>?@\^_`{|}~-]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

正则表达式的元字符+预定义字符类用例

Meta­character(s)DescriptionExample[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.
\bMatches a zero-width boundary between a word-class character (see next) and either a non-word class character or an edge; same as

(^\w|\w$|\W\w|\w\W).

$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'.
\wMatches an alphanumeric character, including "_";
same as [A-Za-z0-9_] in ASCII, and

[\p{Alphabetic}\p{GC=Mark}\p{GC=Decimal_Number}\p{GC=Connector_Punctuation}]

in Unicode,[47] where the Alphabetic property contains more than Latin letters, and the Decimal_Number property contains more than Arab digits.

$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, _).
\WMatches a non-alphanumeric character, excluding "_";
same as [^A-Za-z0-9_] in ASCII, and

[^\p{Alphabetic}\p{GC=Mark}\p{GC=Decimal_Number}\p{GC=Connector_Punctuation}]

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.
\sMatches 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.
\SMatches 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.
\dMatches 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.'
\DMatches 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'.
\AMatches 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'.
\zMatches 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.

                                                                                                                     

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值