2

I had an issue with this regex:

(\{(([^\p{Space}][^\p{Punct}])+)\})

The problem is in number of chars. If I typing even number of chars it's works, when odd - not. I was trying to replace '+' with '?' or '*', but result still the same. How can I fix this?

I expect from this regex to block such strings: {%,$ #fd}. And allow this: {F} or {F242fFSf23}.

10
  • What are the pattern requirements? What are you trying to match? Currently, it matches a {, then 1 or more repetitions of 2 chars, a non-space and then a non-punctuation, and then a }, hence you cannot use 1 char in between {...} Commented Nov 8, 2018 at 9:08
  • When you are trying to replace + then how even or odd numbers are coming into the picture? Commented Nov 8, 2018 at 9:09
  • @WiktorStribiżew I'm trying to block user from entering such string: {%F ,2}. And allow only to type: {Ffrgr2443fdfd} Commented Nov 8, 2018 at 9:09
  • Try \{[^\p{Punct}\p{Space}]+\} or \{[^\p{P}\p{S}\s]+\} or even \{\p{Alnum}+\} or \{[A-Za-z0-9]+\} Commented Nov 8, 2018 at 9:11
  • @WiktorStribiżew You're awesome. First and second regex working. Thank you! Commented Nov 8, 2018 at 9:14

2 Answers 2

2

Currently, it matches a {, then 1 or more repetitions of 2 chars, a non-space and then a non-punctuation, and then a }, hence you cannot use 1 char in between {...}.

To fix that, you need to use both the character classes inside bracket expression:

\{[^\p{Punct}\p{Space}]+\} 

or

\{[^\p{P}\p{S}\s]+\}

Details

  • \{ - a { char
  • [^\p{Punct}\p{Space}]+ - 1 or more repetitons (+) of any char that does not belong to the \p{Punct} (punctuation) or \p{Space} (whitespace) class.
  • \} - a }.

Note that if the contents between the braces can only include ASCII letters or digits (in regex, [A-Za-z0-9]+), you may even use a mere

\{[A-Za-z0-9]+\}
Sign up to request clarification or add additional context in comments.

Comments

0

Disassembling your regex... the reason why it only accepts an even number in between is the following part:

([^\p{Space}][^\p{Punct}])+

This basically means: something which isn't a space, exactly 1 character and something which isn't a ~punct, exactly 1 character and this several times... so exactly 1 + exactly another 1 are exactly 2 characters... and this several times will always be even.

So what you probably rather want is the following:

[^\p{Space}\p{Punct}]+

for the part shown above... which will result in the following for your complete regex:

\{[^\p{Space}\p{Punct}]+}

that of course can be simplified even more. I leave that up to you.

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.