“正则表达式 元字符 限定符”的版本间的差异
跳到导航
跳到搜索
Jihongchang(讨论 | 贡献) |
Jihongchang(讨论 | 贡献) |
||
第103行: | 第103行: | ||
</syntaxhighlight><syntaxhighlight lang="console"> | </syntaxhighlight><syntaxhighlight lang="console"> | ||
找到:aaa | 找到:aaa | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | |||
+ | |||
+ | === 示例3:在 "1111111aaahello" 中找 1{4} === | ||
+ | <syntaxhighlight lang="java"> | ||
+ | import java.util.regex.Matcher; | ||
+ | import java.util.regex.Pattern; | ||
+ | |||
+ | public class RegExp05 { | ||
+ | |||
+ | public static void main(String[] args) { | ||
+ | |||
+ | String content = "1111111aaahello"; | ||
+ | |||
+ | String regStr = "1{4}"; //表示匹配 4 个连续的字符1,等价与 1111 | ||
+ | |||
+ | Pattern pattern = Pattern.compile(regStr); | ||
+ | |||
+ | Matcher matcher = pattern.matcher(content); | ||
+ | |||
+ | while (matcher.find()) { | ||
+ | System.out.println("找到:"+ matcher.group(0)); | ||
+ | } | ||
+ | |||
+ | } | ||
+ | |||
+ | } | ||
+ | </syntaxhighlight><syntaxhighlight lang="console"> | ||
+ | 找到:1111 | ||
</syntaxhighlight> | </syntaxhighlight> |
2022年11月17日 (四) 09:50的版本
https://www.bilibili.com/video/BV1Eq4y1E79W?p=11
用于指定其前面的字符和组合项连续出现多少次
符号 | 含义 | 示例 | 说明 | 匹配输入 |
---|---|---|---|---|
* | 指定字符重复0次或n次(无要求) | (abc)* | 仅包含任意个abc的字符串,等效于 \w* | abc、abcabcabc |
+ | 指定字符重复1次或n次(至少1次) | m+(abc)* | 以至少1个m开头,后接任意个abc的字符串 | m、mabc、mabcabc |
? | 指定字符重复0次或1次(最多1次) | m+abc?
注意:abc没有用括号括起来,?就只会作用在离它最近的字符 c |
以至少1个m开头,后接ab或abc的字符串 | mab、mabc、mmmab、mmabc |
{n} | 只能输入n个字符 | [abcd]{3} | 由abcd中字母组成的任意长度为3的字符串 | abc、dbc、adc |
{n,} | 指定至少 n 个匹配 | [abcd]{3,} | 由abcd中字母组成的任意长度不小于3的字符串 | aab、dbc、aaadbc |
{n,m} | 指定至少n个但不多于m个匹配 | [abcd]{3,5} | 由abcd中字母组成的任意长度不小于3,不大于5的字符串 | abc、abcd、aaaaa、bcdab |
示例1:在 "1111111" 中找 a{3}
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegExp05 {
public static void main(String[] args) {
String content = "1111111";
String regStr = "a{3}"; //表示匹配 3 个连续的字符a,等价与 aaa
Pattern pattern = Pattern.compile(regStr);
Matcher matcher = pattern.matcher(content);
while (matcher.find()) {
System.out.println("找到:"+ matcher.group(0));
}
}
}
因为没有对应的内容,所以控制台什么都不输出
示例2:在 "1111111aaahello" 中找 a{3}
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegExp05 {
public static void main(String[] args) {
String content = "1111111aaahello";
String regStr = "a{3}"; //表示匹配 3 个连续的字符a,等价与 aaa
Pattern pattern = Pattern.compile(regStr);
Matcher matcher = pattern.matcher(content);
while (matcher.find()) {
System.out.println("找到:"+ matcher.group(0));
}
}
}
找到:aaa
示例3:在 "1111111aaahello" 中找 1{4}
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegExp05 {
public static void main(String[] args) {
String content = "1111111aaahello";
String regStr = "1{4}"; //表示匹配 4 个连续的字符1,等价与 1111
Pattern pattern = Pattern.compile(regStr);
Matcher matcher = pattern.matcher(content);
while (matcher.find()) {
System.out.println("找到:"+ matcher.group(0));
}
}
}
找到:1111