Python 中的 Regex 用於在以大寫字母開頭的單詞之間放空格
我們在這裡嘗試解決的問題是將駝峰式大小寫轉換為獨立的單詞。我們可以透過找到給定字串中所有出現的大寫字母並在其之前放一個空格,直接使用正則表示式來解決這個問題。我們可以使用 re 模組中的 sub 方法。
例如,對於輸入字串 -
AReallyLongVariableNameInJava
我們應該獲得以下輸出 -
A Really Long Variable Name In Java
我們可以使用正則表示式 "[A-Z]" 來找到所有大寫字母,然後用空格和該字母再次替換它們。我們可以使用 re 包按如下方式實現它 -
示例
import re
# Find and capture all capital letters in a group and make that replacement
# using the \1 preceded by a space. Strip the string to remove preceding
# space before first letter.
separated_str = re.sub("([A-Z])", " \1", "AReallyLongVariableNameInJava").strip()
print(separated_str)產出
這將產生以下輸出 -
A Really Long Variable Name In Java
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP