Regular expression to match hyphenation

How can I extract wrapped strings from this string?

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

I just want to extract "ADW-CFS-WE" from it, but over the past few hours it has not been very successful. I am stuck in this simple regEx "(. *)", Which resulted in the entire string being specified in the selected.

+6
source share
4 answers

Perhaps you can use:

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

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

A regular expression trick is often specific. Usage .* Will often match.

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

Please note that in these solutions only capital letters AZ are allowed. If not, insert the correct character class. For example, if you want to allow arbitrary letters (for example, a and Ä), replace [AZ] with \p{L} .

+1
source

Just understand all the free words [^ \ s], at least with the help of "-".

This expression will produce the following expression:

 <?php $z = "ADW-CFS-WE CI SLA Def No SLANAME CI Max Outage Service"; $r = preg_match('#([^\s]*-[^\s]*)#', $z, $matches); var_dump($matches); 
0
source

The following template assumes that the data is at the beginning of the line, contains only uppercase letters, and may contain a hyphen in front of each group of one or more of these letters:

  <?php $str = 'ADW-CFS-WE CI SLA Def No SLANAME CI Max Outage Service'; if (preg_match('/^(?:-?[AZ]+)+/', $str, $matches) !== false) var_dump($matches); 

Result:

  array(1) { [0]=> string(10) "ADW-CFS-WE" } 
0
source

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


All Articles