正则表达式划线意味着减去/负/或只是短划线检测

时间:2015-02-12 21:51:50

标签: php regex

是否有更简单的方法来检测破折号是否意味着减去/负数/或只是破折号而不是为每个模式运行单独的正则表达式模式搜索?

即;

4-word = dash
word-4 = dash
word-word = dash
4-4 = minus
-4 = negative

是否可以将其合并为一个正则表达式搜索?或者我必须对每个人使用不同的搜索?

1 个答案:

答案 0 :(得分:0)

您可以使用此基于外观的正则表达式:

-(?=\D)|(?<=\D)(?<!^)-

RegEx Demo

-           # Match a literal
(?=\D)      # Lookahead that means match a literal - if not followed by a non-digit
|           # regex alternation (OR)
(?<=\D)     # Lookbehind that means if not preceded by a non-digit
(?!^)       # Negative Lookahead that means not preceded by line start
-           # Match a literal -