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

Examples using quantifiers

Let's look at few examples to understand these basic quantifiers better.

Which regex pattern should be used to match a two-digit year or a four-digit year?

    \d{2}|\d{4}

Which regex pattern should be used to match a signed decimal number? The pattern should also match a signed integer number:

    ^[+-]?\d*\.?\d+$

Here is the breakup of the preceding regex pattern:

  • The ^ and $ symbols are the start/end anchors
  • The [+-]? pattern makes either the + sign or the - sign (optional because of ?) at the start
  • The \d* pattern matches zero or more digits
  • The \.? pattern matches an optional dot (.) literally
  • The \d+ pattern matches one or more digits

The preceding regex will match all of these inputs:

  • .45
  • 123789
  • 5
  • 123.45
  • +67.66
  • -987.34

What would be the regex to match a number that is at least 10 but not more than 9999?

    ^\d{2,4}$

Since we have a minimum of two digits, 10 is the smallest match, whereas the maximum number of digits allowed is four, and hence, 9999 is the highest match.

What is the regex for an input that has seven digits and that can have + or - at the start?

    ^[+-]?\d{7}$

The [+-]? pattern makes it an optional match at the start before we match the seven digits using \d{7}.

The preceding regex can also be written as ^[+-]?[0-9]{7}$, as \d is a shorthand property to match [0-9]
主站蜘蛛池模板: 郯城县| 舟曲县| 长沙县| 罗甸县| 龙川县| 双鸭山市| 乐亭县| 九寨沟县| 常德市| 泗洪县| 鸡泽县| 天门市| 府谷县| 漯河市| 泾源县| 浦江县| 江川县| 交口县| 通化县| 高州市| 乌审旗| 洪泽县| 盐边县| 彝良县| 芦山县| 潞西市| 娱乐| 陈巴尔虎旗| 南郑县| 姚安县| 龙陵县| 广水市| 蓝山县| 湾仔区| 景宁| 塔城市| 垫江县| 佛冈县| 乐昌市| 吕梁市| 廉江市|