Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

regex - Get the string between [ brackets and special characters in python

I have a really similar question to this one.

And i really wonder why my restult is: NaN.

I have a dataframe which this column:

Action
Player[J?, K?] won the $5.40 main pot with a Straight
Player [5, 2] won the $21.00 main pot with a flush

and I want to built a new column with the cards, who got played:

[J?, K?]
[5, 2]

or even:

[J, K]
[5, 2]

However when I play around on regex and i use: dfpot['cards'] = dfpot['Action'].str.extract(r'[([A-Za-z0-9_]+)]', expand=False)

I only got NaN.

question from:https://stackoverflow.com/questions/66064733/get-the-string-between-brackets-and-special-characters-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can add the characters to the character class in the capture group as in your pattern [([A-Za-z0-9_????, ]+)] or make the pattern a bit more specific:

[([A-Za-z0-9_][????]?,s*[A-Za-z0-9_][????]?)]

The pattern matches:

  • [ Match [
  • ( Capture group 1
    • [A-Za-z0-9_] Match one of the listed charss
    • [????]? Optionally match one of the listed chars
    • ,s*[A-Za-z0-9_][????]? Match a comma and the same logic as before the comma
  • ) Close group 1
  • ] Match ]

Regex demo

For example

import pandas as pd

dfpot = pd.DataFrame({'Action':['Player[J?, K?] won the $5.40 main pot with a Straight', 'Player [5, 2] won the $21.00 main pot with a flush']})
dfpot['cards'] = dfpot['Action'].str.extract(r'[([A-Za-z0-9_][????]?,s*[A-Za-z0-9_][????]?)]', expand=False)
print(dfpot)

Output

                                              Action   cards
0  Player[J?, K?] won the $5.40 main pot with a S...  J?, K?
1  Player [5, 2] won the $21.00 main pot with a f...    5, 2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...