Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Find cases of List["str"] but not List[str] = ["a"]

I'm trying to check for outdated type hints syntax in a Python codebase.

I would like to catch cases such as

List["str"]

which could just be

List[str]

I've written the following regular expression:

List[.*".+".*]

however, it also catches the following string:

List[str] = ["a"]

which I don't want to catch.

Examples of strings I want to catch:

  • List["str"]
  • Union[int, "np.ndarray"]

How could I modify my regular expression accordingly?


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

1 Reply

0 votes
by (71.8m points)

To match the example strings, you could match either List or Union followed by using a negated character class matching from the opening till closing square bracket that can not be followed by an equals sign.

(?:List|Union)[[^][]*](?!s*=)

Explanation

  • (?:List|Union) Match either List or union preceded by a word boundary to prevent them being part of a longer word.
  • [[^][]*] Match from [ till ] not matching either of them in between using a negated character class
  • (?!s*=) Assert no = sign to the right

Regex demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...