2

I need help to generate regex so that it will match any string which has following detail correct:

  1. String should end with bracket and only numbers inside it.
  2. End bracket should appear only once at the end of line and not any where else.
  3. Any characters are allowed before bracket start
  4. No characters are allowed after bracket end
  5. String should contain only 1 set of brackets with numbers, i.e. no double brackets like (( or ))

I have tried this .\([0-9]+\)$ but this is not what i required.

For example:

Following string should match:

asds-xyz (1)
asds+-xyz (12)
as@ds-xyz (123)

Following strings should not be matched:

asds-xyz ((1)
asds-xyz ((12sdf))
(123) asds-xyz
xyz ((2)
XYX (1))
XYZ (1)(2)
xyz(1)BXZ
xyz(1)BXZ(2)

3 Answers 3

2
^[^\(\)]*\(\d+\)$

will do the job...

\d = [0-9]

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Its working fine with test strings. negate group is what i was missing
1

I try to fix with minimum change to your pattern: you have to use the [^ key to exclude brackets before your only desired bracket. like this

[^\(\)]*\([0-9]+\)$

That would find the patterns you like, and if you like the whole string to be like that, then simply add a ^ in the beginning

3 Comments

It matches XYZ (1)(2), asds-xyz ((1), xyz ((2) and xyz(1)BXZ(2) but shouldn't.
@Verarind no, with ^ in the beginning it will not
test it! Your regex says no bracket [^\(\)] for any times *. Any could be zero and that happens in all of the specified cases. But what's about the second fact that a brace shouln'd come anywhere in the string but the end? You need an ancor ^ that all from begining should not be a bracked. But this ancor is missing.
-1

Starting from your regex: .\([0-9]+\)$ . match everything but you need quantifier for this. So add * to this .*\([0-9]+\)$ But the problem is, it will match ( and ) before the last bracket like xyz ((2) So make a negative set for this, the final result:

^(.*[^\(\)])(\([0-9]+\))$

1 Comment

It matches xyz(1)BXZ(2) but shouldn't.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.