官术网_书友最值得收藏!

  • Java 9 Regular Expressions
  • Anubhava Srivastava
  • 408字
  • 2021-07-02 18:58:34

Some basic regular expression examples

Let's look at some basic examples of regular expressions:

    ab*c

This will match a, followed by zero or more b, followed by c.

    ab+c

This will match a followed by one or more b, followed by c.

    ab?c

This will match a followed by zero or one b, followed by c. Thus, it will match both abc or ac.

    ^abc$

This will match abc in a line, and the line must not have anything other than the string abc due to the use of the start and end anchors on either side of the regex.

    a(bc)*z

This will match a, followed by zero or more occurrences of the string bc, followed by z. Thus, it will match the following strings: az, abcz, abcbcz, abcbcbcz, and so on.

    ab{1,3}c

This will match a, followed by one to three occurrences of b, followed by c. Thus, it will match following strings: abc, abbc, and abbbc.

    red|blue

This will match either the string red or the string blue.

    \b(cat|dog)\b

This will match either the string cat or the string dog, ensuring both cat and dog must be complete words; thus, it will fail the match if the input is cats or dogs.

    [0-9]

This is a character class with a character range. The preceding example will match a digit between 0 and 9.

    [a-zA-Z0-9]

This is a character class with a character range. The preceding example will match any alpha-numeric character.

    ^\d+$

This regex will match an input containing only one or more digits.

    ^\d{4,8}$

This regex will allow an input containing four to eight digits only. For example, 1234, 12345, 123456, and 12345678 are valid inputs.

    ^\d\D\d$

This regex not only allows only one digit at the start and end but also enforces that between these two digits there must be one non-digit character. For example, 1-5, 3:8, 8X2, and so on are valid inputs.

    ^\d+\.\d+$

This regex matches a floating point number. For example, 1.23, 1548.567, and 7876554.344 are valid inputs.

    .+

This matches any character one or more times. For example, qwqewe, 12233, or f5^h_=!bg are all valid inputs:

    ^\w+\s+\w+$

This matches a word, followed by one or more whitespaces, followed by another word in an input. For example, hello word, John Smith, and United Kingdom will be matched using this regex.

Engine is a term often used for an underlying module that evaluates the provided regular expression and matches the input string.
主站蜘蛛池模板: 苏尼特左旗| 河曲县| 兴仁县| 湘西| 舟曲县| 宁远县| 新营市| 广东省| 山阴县| 温泉县| 肇庆市| 宜兰市| 平度市| 西充县| 北川| 长沙市| 石河子市| 新巴尔虎左旗| 泸西县| 五寨县| 通河县| 黄冈市| 青川县| 凤庆县| 霍山县| 桐城市| 绥化市| 乐安县| 府谷县| 那曲县| 金沙县| 武山县| 漾濞| 湟源县| 洪江市| 宜兴市| 时尚| 临洮县| 河池市| 农安县| 博野县|