regex

regex for expression with one separator hyphen


I'm going to use regex for matching expressions, which:

  1. Separated by one (and only one) hyphen
  2. Each of the two parts do not contain any spaces

So, it matches:

ss-ss
12-s2
11-11
%@2s-#1

And does not match:

s s-ss
ss-s s
s s-s s
1 s-1s
1s-1 s
1 s-1 s
ss-ss-ss
s1-s2-s3

Is there any way to create with regex?

I tries something like:

^.[^ ]-[^ ]*

But it matches only expressions with any number of hyphens, and whatever space occurrence, for example

 ss-ss-ss
 1 s-1 s

Solution

  • The regex:

    '^[^\ \-]+\-[^\ \-]+$'
    

    should do what you want. Here's the test that I did:

    $ cat x.tst
    ss-ss
    12-s2
    11-11
    %@2s-#1
    s s-ss
    ss-s s
    s s-s s
    1 s-1s
    1s-1 s
    1 s-1 s
    ss-ss-ss
    s1-s2-s3
    
    $ egrep  '^[^\ \-]+\-[^\ \-]+$' x.tst
    ss-ss
    12-s2
    11-11
    %@2s-#1
    
    $ egrep  -v '^[^\ \-]+\-[^\ \-]+$' x.tst
    s s-ss
    ss-s s
    s s-s s
    1 s-1s
    1s-1 s
    1 s-1 s
    ss-ss-ss
    s1-s2-s3
    

    An Explanation:

    The problem is to recognize two non-empty strings separated by a hyphen. Those two strings can't have spaces or hyphens.

    We want that regex twice, separated by a hyphen.

    ^ at the front and $ at the end mean that the match has to extend for the entire string.

    Without the ^ and $, "1 s-1 s" would be a match because the "s-1" in the middle would match the regex.