1

I want to check if a string contains exactly 1 alphabetic char, that may or may not be preceded by any of ~, ! or ?. The expression I have set to match against is:

if (this.str.matches("[!~?]{1,9}?[a-z]{1}")) {

but when the input I have (this.str) is equal to 'p', this if block is not triggered. What am I doing wrong?

Some strings that should match:

!!~?p
p
~p
???!!?!??!~p

Thanks heaps :)

4
  • 1
    If the punctuation symbol (!, ~ and ?) can be optional (can be absent), use "[!~?]{0,9}[a-z]". Or even "[!~?]*[a-z]" where * means 0 or more occurrences. Commented Nov 8, 2018 at 21:30
  • Would ~!???~~!!x be valid? If the "alphabetic char" can only preceded by 1 character, use "[!~?]?\\p{L}", where \\p{L} means any Unicode letter, not just a-z. Commented Nov 8, 2018 at 21:33
  • 1
    Please update your question with a set of strings that should and should not match for the desired outcome Commented Nov 8, 2018 at 21:34
  • Ah I see. Thank you so much! Commented Nov 8, 2018 at 21:34

1 Answer 1

1

I think you need [!~?]{0,9}?[a-z]. The issue was the {1,9} matches ~, !, or ? ONE to nine times. You state that its optional and therefore should be ZERO to nine times.

Try your regex out at https://regex101.com/r/m1ad8X/1.

Try @WiktorStribiżew correction at https://regex101.com/r/m1ad8X/2

And my solution at https://regex101.com/r/m1ad8X/3

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

Comments

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.