Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to match hyphenated words

Tags:

regex

php

How can I extract hyphenated strings from this string line?

ADW-CFS-WE CI SLA Def No SLANAME CI Max Outage Service

I just want to extract "ADW-CFS-WE" from it but has been very unsuccessful for the past few hours. I'm stuck with this simple regEx "(.*)" making the all of the string stated about selected.

like image 745
Kevin Avatar asked Sep 02 '11 06:09

Kevin


Video Answer


2 Answers

You can probably use:

preg_match("/\w+(-\w+)+/", ...)

The \w+ will match any number of alphanumeric characters (= one word). And the second group ( ) is any additional number of hyphen with letters.

The trick with regular expressions is often specificity. Using .* will often match too much.

like image 177
mario Avatar answered Sep 30 '22 11:09

mario


$input = "ADW-CFS-WE X-Y CI SLA Def No SLANAME CI Max Outage Service";
preg_match_all('/[A-Z]+-[A-Z-]+/', $input, $matches);
foreach ($matches[0] as $m) {
  echo $matches . "\n";
}

Note that this solutions assumes that only uppercase A-Z can match. If that's not the case, insert the correct character class. For example, if you want to allow arbitrary letters (like a and Ä), replace [A-Z] with \p{L}.

like image 41
phihag Avatar answered Sep 30 '22 10:09

phihag