Regex to match 3 parts of a given string

Input Example:

hjkhwe5boijdfg

I need to break this down into 3 variables, as shown below:

  • hjkhwe5 (any length always ends with some number (there can be any number))
  • b (always one letter, can be any letter)
  • oijdfg (all that remains at the end, numbers or letters in any combination)

I have a PHP setup preg_match, but I have no idea how complicated this regular expression is. Can anyone give me a hand?

+3
source share
2 answers

Try:

$str = 'hjkhwe5boijdfg';
preg_match("/^([a-z]+\d+)([a-z])(.*)$/", $str, $m);
print_r($m);

output:

Array
(
    [0] => hjkhwe5boijdfg
    [1] => hjkhwe5
    [2] => b
    [3] => oijdfg
)

Explanation:

^           : begining of line
  (         : 1rst group
    [a-z]+  : 1 or more letters
    \d+     : followed by 1 or more digit
  )         : end of group 1
  (         : 2nd group
    [a-z]   : 1 letter
  )         : end group 2
  (         : 3rd group
    .*      : any number of any char
  )         : end group 3
$
+1
source

You can use preg_match as:

$str = 'hjkhwe5boijdfg';
if(preg_match('/^(\D*\d+)(\w)(.*)$/',$str,$m)) {
        // $m[1] has part 1, $m[2] has part 2 and $m[3] has part 3.
}

Look it up

0
source

Source: https://habr.com/ru/post/1786642/


All Articles