> For the complete documentation index, see [llms.txt](https://stb11816.gitbook.io/python_note/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://stb11816.gitbook.io/python_note/web/re.md).

# re

[簡易範例](http://webber-pypyso.blogspot.tw/2011/02/10-1-2.html)

```python
#簡易搜尋範例
import re

test = 'hello re!!!' #要被檢查的句子
pattern = re.compile(r'.{1}re.{1}') #搜尋條件：尋找re並包含前後一個任意字元

match = pattern.search(test)
if match: #找不到則為None
    print(match.group()) #輸出結果： re!(包含前一個空格)


#簡易取代範例
pattern2 = re.compile(r're') #條件：找到re
print(pattern2.sub('RE',test)) #將字串中的re取代為RE，輸出結果：hello RE!!!
```

爬蟲應用：剔除文章的html標籤

```python
import re

def remove_html_tags(data): #data為網頁原始碼
    p = re.compile(r'<.*?>')
    return p.sub('', data)

test = '<h1>123</h2>'
print(remove_html_tags(test)) #輸出結果：123
```

語料處理應用：

```python
import re

test='今天天氣很好，覺得肚子很餓，粗乃玩'
pattern=re.compile(r'，.*肚子.*，') #包含肚子的一句話
result=pattern.search(test)

print(result.group()) #搜尋結果：，覺得肚子很餓，
```

判斷語言種類：

```python
import re

test=u'abc找中文abc'
pattern=re.compile(u'[\u4e00-\u9fa5]+') #'+':一個或多個，找到一個或多個中文字
result=pattern.search(test)

print(result.group()) #搜尋結果：找中文
```

字串與pattern需要是相同編碼

擷取斷詞結果詞性

```python
#python3
import re

test='a3(neu) sss(Neu) ((PARENTHESISCATEGORY) )(PARENTHESISCATEGORY)' #假設斷詞結果
pattern=re.compile(r'\([a-z,A-Z,_,0-9]+\)') #加斜線就可連同括弧一起比對

match =pattern.findall(test)
match2=pattern.search(test)

print(match)         #['(neu)', '(Neu)', '(PARENTHESISCATEGORY)', '(PARENTHESISCATEGORY)']  如果找不到則回傳空陣列
print(match2.group())#(neu)   只會找第一個
```

使用特定符號分隔

```python
#python3
import re
raw='123\n456。789'
sentences=re.split('\n|。', raw)

print(sentences) #['123', '456', '789']

raw2='123\n456\n789' #只出現斷行符號
sentences2=re.split('\n|。', raw)

print(sentences2) #['123', '456', '789']
```

尋找url

```python
# 找圖片
raw_content = "test content"
urls = re.findall('(?:http\:|https\:)?\/\/.*\.(?:png|jpg)', raw_content)

# 找url
all_url = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\), ]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', raw_article)
```

<https://stackoverflow.com/questions/40813850/python-2-7-regex-for-image-url>

<https://www.geeksforgeeks.org/python-check-url-string/>

讀取所有查詢結果的indx位置

```python
import re
term_pat = re.compile(r'(＜FRONT＞)([.\n\w\W]*?)(＜END＞)')
get_term = term_pat.finditer(sttr_replace)

# 將計算結過存入字典
for idx, term in enumerate(get_term):
    # print(term)
    start = term.start()
    end = term.end()
    print(term, start, end)


# solution 2
iter = re.finditer(r"\bis\b", String)
indices = [m.start(0) for m in iter]
```

<https://stackoverflow.com/questions/3519565/find-the-indexes-of-all-regex-matches>

<https://stackoverflow.com/questions/2674391/python-locating-the-position-of-a-regex-match-in-a-string/16360404>

過濾特殊字符

<https://blog.csdn.net/jlulxg/article/details/84650683>

[符號資訊](https://atedev.wordpress.com/2007/11/23/正規表示式-regular-expression/)

[完整教學](http://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html)\
<https://docs.python.org/2/library/re.html>\
有些在控制字符中
