正则表达式 定义字符串的搜索模式。对于给定的字符串,此模式可能匹配一次或多次或根本不匹配。正则表达式的缩写是regex。正则表达式可用于搜索、编辑和操作文本。
正则表达式支持一些具有明确预定义含义的元字符或特殊字符。以下元字符使某些常见模式更易于使用,例如'd'
而不是 [0..9]
。
元字符 | 描述 |
d | 任意数字,[0-9]的简写 |
D | 非数字,[^0-9]的简写 |
s | 一个空白字符,[tnx0brf]的缩写 |
小号 | 非空白字符,[^s]的简称 |
w | 单词字符,[a-zA-Z_0-9]的简写 |
W | 一个非单词字符[^w] |
S+ | 几个非空白字符 |
b | 匹配单词边界。单词字符是 [a-zA-Z0-9_] 并且 b 匹配它的边界。 |
package com.howtodoinjava.regex; import junit.framework.Assert; import org.junit.Test; public class MetaCharactersTest { @Test public void testAnyDigit() { /** * Matches exactly 3 digits * */ String sampleText = "123"; String regex = "d{3}"; Assert.assertEquals(true, sampleText.matches(regex)); } @Test public void testNonDigit() { /** * Matches exactly 3 non digits * */ String sampleText = "abc"; String regex = "d{3}"; Assert.assertNotSame(true, sampleText.matches(regex)); } @Test public void testWhiteSpaceCharacters() { /** * Matches n number of spaces * */ String sampleText = " "; String regex = "s{0,}"; Assert.assertEquals(true, sampleText.matches(regex)); } @Test public void testNonWhiteSpaceCharacter1() { /** * Matches no space allowed * */ String sampleText = "abc123"; String regex = "S{0,}"; Assert.assertEquals(true, sampleText.matches(regex)); } @Test public void testNonWhiteSpaceCharacter2() { /** * Matches no space allowed with '+' sign * */ String sampleText = "abc123"; String regex = "S+"; Assert.assertEquals(true, sampleText.matches(regex)); } @Test public void testWordCharacter() { /** * Matches one or more word characters * */ String sampleText = "abc123"; String regex = "w{0,}"; Assert.assertEquals(true, sampleText.matches(regex)); } @Test public void testNonWordCharacter() { /** * Matches one or more word characters * */ String sampleText1 = "abc123"; String sampleText2 = "!@#$"; String regex = "W{0,}"; Assert.assertNotSame(true, sampleText1.matches(regex)); Assert.assertEquals(true, sampleText2.matches(regex)); } @Test public void testWordBoundary() { /** * Matches the word "abc123" exactly same * */ String sampleText = "abc123"; String regex = "babc123b"; Assert.assertEquals(true, sampleText.matches(regex)); } }
在这个 Java 正则表达式示例 中,我们学习了在正则表达式中使用元字符来评估文本字符串。
快乐学习!!
地址:https://www.cundage.com/article/regular-expressions-meta-characters.html