-1

I have to validate a string based on first alpha-numeric character of the string. Certain characters can be part of the string but if they are at beginning then they have to ignored.

For example:

---  BATest- 1   --

should be:

BATest-1

How do I remove dashes from beginning and end but not from middle?

To add to my question: can the first alphanumeric character decide if following alphanumeric characters are to be removed or not?

I.e. If A then nothing would need to be removed and throw a validation error; and yet if B then strip the string as mentioned above.

Mike
  • 1,080
  • 1
  • 9
  • 25
user3075906
  • 725
  • 1
  • 8
  • 19
  • You want to remove the dash characters from the front and end of the string? And you want to remove space characters also? And FWIW: you should post the properly-formatted code that you've written to try to solve the problem. – orde Mar 11 '16 at 19:56
  • Yes, need to remove dashes from front and end, space from whole string. – user3075906 Mar 11 '16 at 20:07
  • This seems like an XY problem. You say the problem you're trying to solve is "[validating] a string based on [its] first alpha-numeric character," but the question you've asked is how to remove dashes from a string. The latter isn't necessarily a good solution to the former, but it's hard to help you when you haven't shown us the code you've written so far. – Jordan Running Mar 11 '16 at 20:08
  • Welcome to SO. Please read "[ask]" including the links at the bottom, and "[mcve]". We'd like to see your effort toward solving the problem. Without that it looks like you're asking us to write the code for you, which is off topic. – the Tin Man Mar 11 '16 at 21:53

2 Answers2

1

You asked to remove the dashes from the beginning and the end:

"--- BATest- 1 --".gsub(/^-+|-+$|\s/, "")
# => "BATest-1"
guitarman
  • 3,290
  • 1
  • 17
  • 27
1
r = /
    --+ # Match at least two hyphens
    |   # or
    \s  # Match a space
    /x  # Free-spacing regex definition mode

'--- BATest- 1 --'.gsub r, ""
  #=> "BATest-1" 
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100