Search code examples
regexpreg-match

Regex to match numbers followed by a specific character


I am so sorry, I know this is a simple question, which is not appropriate here, but I am terrible in regex.

I use preg_match with a pattern of (numbers A) to match the following replaces with the substrings

2A -> <i>2A</i>
100 A -> <i>100 A</i>
84.55A -> <i>84.55A</i>
92.1 A -> <i>92.1 A</i>
  • The numbers can be separated from the character or not
  • The numbers can be decimal
  • The letter should not be the begging of a word (not matching 4 All; in fact, A should be followed by a space or period or linebreak)

My problem is to apply OR conditions to match a character which may exist or not to have a single match to be replaced as

$str = preg_replace($pattern, '<i>$1</i>', $str);

Solution

  • I can suggest

    '~\b(?<![\d.])\d*\.?\d+\s*A\b~'
    

    See the regex demo. Replace with '<i>$0</i>' where the $0 is the backreference to the whole match.

    Details:

    • \b - leading word boundary
    • (?<![\d.]) - a negative lookbehind that fails the match if there is a dot or digit before the current location (NOTE: this is added to avoid matching 33.333.4444 A like strings, just remove if not necessary)
    • \d*\.?\d+ - a usual simplified float/int value regex (0+ digits, an optional . and 1+ digits) (NOTE: if you need a more sophisticated regex for this, see Matching Floating Point Numbers with a Regular Expression)
    • \s* - 0+ whitespaces
    • A\b - a whole word A (here, \b is a trailing word boundary).