도입
정규식 (正規式, Regular Expression)은 특정한 규칙을 가진 문자열의 집합을 표현하는 데 사용하는 형식 언어입니다. 이걸 잘 써야 당장 코드 라인이 줄겠죠. 지금부터 정규식 사용법을 구체적으로 알아보고, 활용 방안의 예시를 베껴서 기록하고자 합니다.
정규식 쓰임
-
- PHP의 preg_match 함수
-
$subject = "abcdef"; $pattern = '/^def/'; preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3); print_r($matches);
-
- C#의 RegEx 클래스
-
class TestRegularExpressionValidation { static void Main() { string[] numbers = { "123-555-0190", "444-234-22450", "690-555-0178", "146-893-232", "146-555-0122", "4007-555-0111", "407-555-0111", "407-2-5555", }; string sPattern = "^\\d{3}-\\d{3}-\\d{4}$"; foreach (string s in numbers) { System.Console.Write("{0,14}", s); if (System.Text.RegularExpressions.Regex.IsMatch(s, sPattern)) { System.Console.WriteLine(" - valid"); } else { System.Console.WriteLine(" - invalid"); } } // Keep the console window open in debug mode. System.Console.WriteLine("Press any key to exit."); System.Console.ReadKey(); } } /* Output: 123-555-0190 - valid 444-234-22450 - invalid 690-555-0178 - valid 146-893-232 - invalid 146-555-0122 - valid 4007-555-0111 - invalid 407-555-0111 - valid 407-2-5555 - invalid */
-
- PHP의 preg_match 함수
-
- Java의 RegEx 클래스
-
import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexMatches { public static void main( String args[] ) { // String to be scanned to find the pattern. String line = "This order was placed for QT3000! OK?"; String pattern = "(.*)(\\d+)(.*)"; // Create a Pattern object Pattern r = Pattern.compile(pattern); // Now create matcher object. Matcher m = r.matcher(line); if (m.find( )) { System.out.println("Found value: " + m.group(0) ); System.out.println("Found value: " + m.group(1) ); System.out.println("Found value: " + m.group(2) ); }else { System.out.println("NO MATCH"); } } }
-
- Java의 RegEx 클래스
- javascript 리터럴 또는 RegExp 클래스
-
var myRe = /d(b+)d/g; var myArray = myRe.exec("cdbbdbsbz");
-
- URL Rewrite Rule
-
rewrite ^/blog/sitemap(-+([a-zA-Z0-9_-]+))?\.xml$ "/blog/sitemap$2.xml" last; rewrite ^/blog/sitemap(-+([a-zA-Z0-9_-]+))?\.xml$ "/blog/index.php?xml_sitemap=params=$2" last; rewrite ^/blog/sitemap(-+([a-zA-Z0-9_-]+))?\.xml\.gz$ "/blog/index.php?xml_sitemap=params=$2;zip=true" last; rewrite ^/blog/sitemap(-+([a-zA-Z0-9_-]+))?\.html$ "/blog/index.php?xml_sitemap=params=$2;html=true" last; rewrite ^/blog/sitemap(-+([a-zA-Z0-9_-]+))?\.html.gz$ "/blog/index.php?xml_sitemap=params=$2;html=true;zip=true" last;
-