0

For example String is '10S#9D7T*'.
My desire result is 3 arrays. [('10S#'), ('9D'), ('7T*')]

There are 3 condition.

  1. First one or two digit range is 0~10 always.
  2. And follow one character is located always.
  3. And follow '#' or '*'. But it is not essential.

That is my code.

rex = re.compile(r'\d?\d\w?[\*\#]')
str = '10S#9D7T'
print(rex.findall(str))

Acutal Result -> ['10S#']

There is only one array.

please fixed my regex pattern.

1
  • 1
    Your example string does not contain a *, and [*#] does not have a ? after so you enforce one of these after the match. Just add a * in your string and a ? after the [*#]. Note you do not need to escape the * in the brackets. Commented Jan 15, 2019 at 13:36

2 Answers 2

1

You could change \d?\d to \d{1,2} and as the following character is always there it should not be optional so you could omit the question mark. The * and # do not have to be escaped in the character class and add a quesion mark to that to make it optional.

You might use:

\d{1,2}\w[*#]?

That will match:

  • \d{1,2} Match 1-2 digits
  • \w Match a word character
  • [*#]? Optional character class to match one of * or #

    import re str = "10S#9D7T*" rex = re.compile(r'\d{1,2}[A-Z][*#]?') print(rex.findall(str))

Result

['10S#', '9D', '7T*']

Regex demo | Python demo

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

Comments

1

You can get three results by making the [*#] class optional. (Also, note that those characters don't need to be escaped.)

str = '10S#9D7T*'
rex = re.compile(r'\d?\d\w?[*#]?')
print(rex.findall(str))

Result: ['10S#', '9D', '7T*']

As for your second rule, "And follow one character is located always," you probably want to make the \w non-optional by removing the ? directly after it.

r'\d?\d\w[*#]?'

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.