Python 正規表示式
特殊符號「^」和「$」
以上兩個特殊符號,適用於Python
和JavaScript
,不適用於Java
。
^
會比對目標字串的起始位置,要含有^
後面的字串,才算匹配成功。$
會比對目標字串的結尾位置,要含有$
前面的字串,才算匹配成功。
無特殊符號
- 只要目標字串任一位置符合
pattern
,則為true
。 Python
的pattern = 'Bob'
,等價於Java
的pattern = '.*Bob.*'
。
Python Example:
import re
pattern = 'Bob'
string1 = 'I am Bob'
string2 = 'Bob is me'
#此方式能達到 pattern obj reuse
prog = re.compile(pattern)
prog.search(string1) #result = Match
prog.search(string2) #result = Match
#此方式等價於上面方式
re.search(pattern, string1) #result = Match
re.search(pattern, string2) #result = Match
Java Example:
String pattern1 = ".*Bob.*";
String string1 = "I am Bob";
String string2 = "Bob is me";
string1.matches(pattern1); //result = true
string2.matches(pattern1); //result = true
「^」符號
^
會比對目標字串的起始位置,要含有^
後面的字串,才算匹配成功。Python
的pattern = '^Bob'
,等價於Java
的pattern = 'Bob.*'
。
Python Example:
import re
pattern = '^Bob'
string1 = 'I am Bob'
string2 = 'Bob is me'
prog = re.compile(pattern)
prog.search(string1) #result = None
prog.search(string2) #result = Match
Java Example:
String pattern1 = "Bob.*";
String string1 = "I am Bob";
String string2 = "Bob is me";
string1.matches(pattern1); //result = false
string2.matches(pattern1); //result = true
「$」符號
$
會比對目標字串的結尾位置,要含有$
前面的字串,才算匹配成功。Python
的pattern = 'Bob$'
,等價於Java
的pattern = '.*Bob'
。
Python Example:
import re
pattern = 'Bob$'
string1 = 'I am Bob'
string2 = 'Bob is me'
prog = re.compile(pattern)
prog.search(string1) #result = Match
prog.search(string2) #result = None
Java Example:
String pattern1 = ".*Bob";
String string1 = "I am Bob";
String string2 = "Bob is me";
string1.matches(pattern1); //result = true
string2.matches(pattern1); //result = false
同時使用「^」和「$」符號
- 目標字串必須完全符合
pattern
,才為true
。 Python
的pattern = '^Bob$'
,等價於Java
的pattern = 'Bob'
。
Python Example:
import re
pattern = '^Bob$'
string1 = 'I am Bob'
string2 = 'Bob is me'
string3 = 'Bob'
prog = re.compile(pattern)
prog.search(string1) #result = None
prog.search(string2) #result = None
prog.search(string3) #result = Match
Java Example:
String pattern1 = "Bob";
String string1 = "I am Bob";
String string2 = "Bob is me";
String string3 = "Bob";
string1.matches(pattern1); //result = false
string2.matches(pattern1); //result = false
string3.matches(pattern1); //result = true