我想在使用数字之前使用正则表达式验证它,但它不起作用。

huangapple go评论84阅读模式
英文:

I want to validate my numbers with regex before using it but it not working out

问题

I want to validate my numbers with regex before using it but it not working out

I want the first digit to start with 0 follow by 2 or 5 and follow by 4 and the rest continue to 10 digit

  1. <?php
  2. $str = "0241310102";
  3. $pattern = "([0]{1}[2,5]{1}[4]{1}[0-9]{7})";
  4. if(preg_match($pattern, $str)){
  5. echo "YES";
  6. }else{
  7. echo "NO";
  8. }
  9. ?>
英文:

I want to validate my numbers with regex before using it but it not working out

I want the first digit to start with 0 follow by 2 or 5 and follow by 4 and the rest continue to 10 digit

  1. &lt;?php
  2. $str = &quot;0241310102&quot;;
  3. $pattern = &quot;([0]{1}[2,5]{1}[4]{1}[0-9]{7})&quot;;
  4. if(preg_match($pattern, $str)){
  5. echo &quot;YES&quot;;
  6. }else{
  7. echo &quot;NO&quot;;
  8. }
  9. ?&gt;

答案1

得分: 1

  1. 你需要将模式锚定到字符串的开头/结尾(^$)。
  2. 单个数字不需要被指定为字符类 [0]0
  3. 量词只需要在与1不同的情况下指定 0{1}0
  4. [2,5] 会包含字符类中的逗号 → [25]
  1. $examples = [
  2. "0241310102",
  3. "1241310102",
  4. "0541310102",
  5. "0551310102",
  6. "0241"
  7. ];
  8. $pattern = '(^0[25]4[0-9]{7}$)';
  9. foreach ($examples as $example) {
  10. echo $example, ": ";
  11. if (preg_match($pattern, $example)) {
  12. echo "YES", "\n";
  13. } else {
  14. echo "NO", "\n";
  15. }
  16. }
英文:
  1. You need to anchor the pattern to the start/end of the string (^, $).
  2. Single digits do not need to be specified as a character class [0]0
  3. Quantifier need only to be specified if different from one 0{1}0
  4. [2,5] would include the comma in the character class → [25]
  1. $examples = [
  2. &quot;0241310102&quot;,
  3. &quot;1241310102&quot;,
  4. &quot;0541310102&quot;,
  5. &quot;0551310102&quot;,
  6. &quot;0241&quot;
  7. ];
  8. $pattern = &#39;(^0[25]4[0-9]{7}$)&#39;;
  9. foreach ($examples as $example) {
  10. echo $example, &quot;: &quot;;
  11. if (preg_match($pattern, $example)) {
  12. echo &quot;YES&quot;, &quot;\n&quot;;
  13. } else {
  14. echo &quot;NO&quot;, &quot;\n&quot;;
  15. }
  16. }

huangapple
  • 本文由 发表于 2023年6月29日 00:21:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76575054.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定