简体   繁体   English

正则表达式动态格式

[英]Regular Expression Dynamic Format

Can some one help me in checking a sting using regular expression: 有人可以帮助我使用正则表达式检查刺痛:

My String will be in any format lets see My String将以任何格式显示

12AAA22TBI 12AAA22TBI

The above Sting is in a format of NNTTTNNTTT 上述Sting的格式为NNTTTNNTTT

Where 哪里

N - Number, T - TEXT N - 数字,T - TEXT

I am able to write a code to check the format in static. 我能够编写一个代码来检查静态格式。 But the format will come dynamic. 但格式将变得动态。

Suppose the second case might be 123456TTT = NNNNNNTTT The Format will be different. 假设第二种情况可能是123456TTT = NNNNNNTTT格式将不同。 Can some one help me to write a regular express with dynamic value; 有人可以帮我写一个具有动态价值的常规快递;

Note: The length of the string as well as the length of the FORMAT will Change. 注意:字符串的长度以及FORMAT的长度将更改。

Pseudo code: 伪代码:

Function ('FORMAT','STRING'){
IF(FORMAT == STRING): Return 1;
ELSE Return 0;
}

FORMAT == STRING Here I need help to check the Format and string using regular expression but dynamically. FORMAT == STRING这里我需要帮助来检查格式和字符串使用正则表达式,但动态。

Example: My Function will be same but the Format and String will differ: 示例:我的函数将相同,但格式和字符串将不同:

1. NNNTTTNN -- 111ABC22
2. TNTNTNTN -- A1B2C3D4
3. TTTTNNNNN -- ABCD12345
4. TTNNTTTTTT -- AB01ABCDEF

The above is some of the examples. 以上是一些例子。

Use the example code below as a start... 使用下面的示例代码作为开始......

$format = 'NNTTTNNTTT';
$value  = '12AAA22TBI';

$format = preg_replace('/[^NT]/', '', $format);
$format = preg_replace('/T/', '[A-Z]', $format);
$format = preg_replace('/N/', '\d', $format);
$format = "/^$format$/";

$match = (preg_match($format, $value));

print "$match\n";

Test it here . 在这里测试一下

I created a simple function that generates a regex, you could simply add rules to support other characters and map them to a specific regex: 我创建了一个生成正则表达式的简单函数,您可以简单地添加规则来支持其他字符并将它们映射到特定的正则表达式:

function generateRegex($input){
    $rules = array(
        'N' => '[0-9]',
        'T' => '[a-zA-Z]',
        // You could add more rules here
    );
    $delimiter = '~';

    $output = strtr($input, $rules); // Replace-Fu
    $output = '^' . $output . '$'; // Add begin and end anchor, comment this line out if you don't want it.
    $output = $delimiter . $output . $delimiter; // Add the delimiters
    return $output; // Should I explain o_O ?
}

A demo : 演示:

$inputArr = array('NNNTTTNN','TNTNTNTN','TTTTNNNNN','TTNNTTTTTT');
foreach($inputArr as $input){
    echo $input . '->' . generateRegex($input) . '<br>';
}

Output: 输出:

NNNTTTNN -> ~^[0-9][0-9][0-9][a-zA-Z][a-zA-Z][a-zA-Z][0-9][0-9]$~
TNTNTNTN -> ~^[a-zA-Z][0-9][a-zA-Z][0-9][a-zA-Z][0-9][a-zA-Z][0-9]$~
TTTTNNNNN -> ~^[a-zA-Z][a-zA-Z][a-zA-Z][a-zA-Z][0-9][0-9][0-9][0-9][0-9]$~
TTNNTTTTTT -> ~^[a-zA-Z][a-zA-Z][0-9][0-9][a-zA-Z][a-zA-Z][a-zA-Z][a-zA-Z][a-zA-Z][a-zA-Z]$~

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM