development

문자, 숫자 및-_에 대한 정규식

big-blog 2020. 10. 9. 11:23
반응형

문자, 숫자 및-_에 대한 정규식


값이 다음 조합 중 하나 인 경우 PHP에서 확인하는 데 문제가 있습니다.

  • 문자 (대문자 또는 소문자)
  • 숫자 (0-9)
  • 밑줄 (_)
  • 대시 (-)
  • 포인트 (.)
  • 공백이 없습니다! 또는 다른 문자

몇 가지 예 :

  • 확인 : "screen123.css"
  • 확인 : "screen-new-file.css"
  • 확인 : "screen_new.js"
  • 비정상 : "screen new file.css"

주어진 문자열에 위에서 언급 한 문자가 아닌 다른 문자가있을 때 오류가 발생해야하기 때문에 정규식이 필요하다고 생각합니다.


원하는 패턴은 다음과 같습니다 ( rubular.com에서 확인 ).

^[a-zA-Z0-9_.-]*$

설명:

  • ^ 라인 앵커의 시작입니다.
  • $ 라인 앵커의 끝입니다.
  • [...] 문자 클래스 정의입니다.
  • * "0 개 이상의"반복

리터럴 대시 -는 문자 클래스 정의의 마지막 문자입니다. 그렇지 않으면 다른 의미 (예 : 범위)를 갖습니다. .또한 문자 클래스 정의 외부에서 다른 의미를 갖지만 내부에서는 리터럴 일뿐입니다..

참고 문헌


PHP에서

다음은이 패턴을 사용하는 방법을 보여주는 스 니펫입니다.

<?php

$arr = array(
  'screen123.css',
  'screen-new-file.css',
  'screen_new.js',
  'screen new file.css'
);

foreach ($arr as $s) {
  if (preg_match('/^[\w.-]*$/', $s)) {
    print "$s is a match\n";
  } else {
    print "$s is NO match!!!\n";
  };
}

?>

위의 인쇄물 ( ideone.com에서 볼 수 있음 ) :

screen123.css is a match
screen-new-file.css is a match
screen_new.js is a match
screen new file.css is NO match!!!

\w대신 사용하면 패턴이 약간 다릅니다 . "단어 문자"의 문자 클래스입니다.

API 참조


사양에 대한 참고 사항

This seems to follow your specification, but note that this will match things like ....., etc, which may or may not be what you desire. If you can be more specific what pattern you want to match, the regex will be slightly more complicated.

The above regex also matches the empty string. If you need at least one character, then use + (one-or-more) instead of * (zero-or-more) for repetition.

In any case, you can further clarify your specification (always helps when asking regex question), but hopefully you can also learn how to write the pattern yourself given the above information.


you can use

^[\w\d_.-]+$

the + is to make sure it has at least 1 character. Need the ^ and $ to denote the begin and end, otherwise if the string has a match in the middle, such as @@@@xyz%%%% then it is still a match.


To actually cover your pattern, i.e, valid file names according to your rules, I think that you need a little more. Note this doesn't match legal file names from a system perspective. That would be system dependent and more liberal in what it accepts. This is intended to match your acceptable patterns.

^([a-zA-Z0-9]+[_-])*[a-zA-Z0-9]+\.[a-zA-Z0-9]+$

Explanation:

  • ^ Match the start of a string. This (plus the end match) forces the string to conform to the exact expression, not merely contain a substring matching the expression.
  • ([a-zA-Z0-9]+[_-])* Zero or more occurrences of one or more letters or numbers followed by an underscore or dash. This causes all names that contain a dash or underscore to have letters or numbers between them.
  • [a-zA-Z0-9]+ One or more letters or numbers. This covers all names that do not contain an underscore or a dash.
  • \. A literal period (dot). Forces the file name to have an extension and, by exclusion from the rest of the pattern, only allow the period to be used between the name and the extension. If you want more than one extension that could be handled as well using the same technique as for the dash/underscore, just at the end.
  • [a-zA-Z0-9]+ One or more letters or numbers. The extension must be at least one character long and must contain only letters and numbers. This is typical, but if you wanted allow underscores, that could be addressed as well. You could also supply a length range {2,3} instead of the one or more + matcher, if that were more appropriate.
  • $ Match the end of the string. See the starting character.

Something like this should work

$code = "screen new file.css";
if (!preg_match("/^[-_a-zA-Z0-9.]+$/", $code))
{
    echo "not valid";
}

This will echo "not valid"


This is the pattern you are looking for

/^[\w-_.]*$/

What this means:

  • ^ Start of string
  • [...] Match characters inside
  • \w Any word character so 0-9 a-z A-Z
  • -_. Match - and _ and .
  • * Zero or more of pattern or unlimited
  • $ End of string

If you want to limit the amount of characters:

/^[\w-_.]{0,5}$/

{0,5} Means 0-5 characters


[A-Za-z0-9_.-]*

This will also match for empty strings, if you do not want that exchange the last * for an +

참고URL : https://stackoverflow.com/questions/3028642/regular-expression-for-letters-numbers-and

반응형