Yasas Ranawaka
Yasas Ranawaka

Reputation: 63

Regular expression to allow only one special character Middle on the string

Need a regex to match below text

testword
testWord
TestA/Test
testt test
TestA-Test

I want to check whether in a given string two texts are joined with a space dash or slash string should start with a test and end with a text These are the possible word

"wordOne/wordTwo"
"wordOne-wordTwo"
"wordOne wordTwo"
"wordOne"

Tried with this. didn't work

^[a-zA-Z][/- ]?[a-zA-Z]

Upvotes: 0

Views: 2582

Answers (2)

The fourth bird
The fourth bird

Reputation: 163362

If you also want to allow a single letter as a word:

^[a-zA-Z]+(?:[\/ -][a-zA-Z]+)?$

Explanation

  • ^ Start of string
  • [a-zA-Z]+
  • (?:[\/ -][a-zA-Z]+)? Optionally match either / - and 1+ chars a-zA-Z
  • $ End of string

Regex demo

Upvotes: 2

Blem
Blem

Reputation: 822

It is a bit hard to understand what you are looking for but it looks like what you want is something more like ^[a-zA-Z]+[\/\- ]?[a-zA-Z]+

You are missing is + after the [a-zA-Z] to indicate there is one or more, and then you need \ infront of - and / to escape

Upvotes: 2

Related Questions