正则表达式大写某些字母

时间:2016-07-30 05:40:14

标签: python regex

如果C代表摄氏度,我想在某些情况下使用正则表达式将字母c大写(例如)。到目前为止我的正则表达式:

$address

示例文字:

$name=Yii::$app->request->post('name');
$address=Yii::$app->request->post('address');
$sql = "SELECT * FROM studentrecords where 1 = 1 ";        
if($name)
{
    $sql.=" AND name='$name'" ;

}
if($address) {
     $sql.= " AND address= '$address'";
    }

$display=Yii::$app->db->createCommand($sql)->queryAll();

我想在数字之后将所有孤独的c和c都大写。任何指针都会有所帮助。

1 个答案:

答案 0 :(得分:0)

您需要(?<=...)代替(?!...),前者代表看后面,而后者代表负面展望,如果您需要要在空格或数字后替换c,那么您需要使用后面的约束:

str1 = "Some plastic insert c lids were cracked, temperature was between 8c and 8.8c."

import re
re.sub(r"(?<=\s)c(?=\s)|(?<=\d)c", "C", str1)
# 'Some plastic insert C lids were cracked, temperature was between 8C and 8.8C.'

根据您定义孤独的方式,单词边界可能更适合:

re.sub(r"\bc\b|(?<=\d)c", "C", str1)
# 'Some plastic insert C lids were cracked, temperature was between 8C and 8.8C.'

更新注释中的案例:

str2 = "Ensure that noodles soaked in water are kept at or 4 c. Noodles are moved to walk in cooler. * Ensure that perishable food is chilled rapidly as * A) temperature from 60 c-20 C must fall within two hrs"

re.sub(r"\bc\b|(?<=\d)c", "C", str2)
# 'Ensure that noodles soaked in water are kept at or 4 C. Noodles are moved to walk in cooler. * Ensure that perishable food is chilled rapidly as * A) temperature from 60 C-20 C must fall within two hrs'