-1

RegEx to validate string with alphabets and for opening and closing parentheses if available with alphabets in it, is not working.

^[a-zA-Z]([a-zA-Z '-.]|(?<=\[)[A-Za-z]+(?=\]))*$

Valid String :- Demo test-demo's [Test-Demo] Valid String :- String's.(SomeStringHere)[SomeStringHere] Invalid String :- 'String()' Invalid String :- 'String)(' Invalid String :- 'String[]' Invalid String :- 'String]['

Shraddha J
  • 25
  • 4
  • 1
    Can you give an example of a string which should be invalidated? – M M Jul 30 '19 at 12:02
  • 2
    are you trying to make sure the sequential parentheses are balanced (if so regex is [not the right way to go](https://stackoverflow.com/a/546457/3462319))? – depperm Jul 30 '19 at 12:03
  • Try `^[a-zA-Z][a-zA-Z '.-]*(?:\([a-zA-Z '.-]+\))?\[[a-zA-Z0-9 '.-]+\]$`, see [demo](https://regex101.com/r/JrSXNe/1). – Wiktor Stribiżew Jul 30 '19 at 12:26
  • Thanks for your solution but the any parentheses should not be compulsory. If any parentheses is there then it should complete the criteria of sequence of parentheses whichever available and alphabets in between it. – Shraddha J Jul 30 '19 at 13:29
  • You say there may only be *alphabets* inside `()` and `[]`, but from the examples, it is clear there can be more than letters. Try just `^[a-zA-Z][a-zA-Z '.-]*(?:\([^()]+\)|\[[^\][]+])*$`, see https://regex101.com/r/JrSXNe/3. Does it work for you? – Wiktor Stribiżew Jul 30 '19 at 13:53
  • Yes you are right, but I want only alphabets, space, apostrophe, dot, hyphen only inside parentheses. Not numbers and other any special characters. – Shraddha J Jul 31 '19 at 07:18

1 Answers1

0

Thanks all of you for your help. Following answer satisfied my question.

^[a-zA-Z](?:([a-zA-Z '.-]+)|[[a-zA-Z '.-]+]|[a-zA-Z '.-])*$

Shraddha J
  • 25
  • 4