C/C++ 正则表达式

在头文件 regex 中有关于正则表达式的实现和接口。

cmatch、smatch 类保存匹配结果。

参考C++标准库中正则表达式的使用

JavaScript 的字符串替换

JavaScrip 的正则不提供字符串替换方法,字符串提供replace 方法,支持正则表达式。

str.replace(oldString/pattern, newString)

正则表达式添加g 参数,实现全部替换。

替换掉文件名在的/、\、(、)、" 符号为-。

var txt= 'path/name("hello\\word)';
console.log(txt.replace(/[\/\\()"]/g, '_'));

PowerShell 的正则表达式

PowerShell 使用Regex 类来实现正则表达式,命名空间是 System.Text.RegularExpressions。在PowerShell 中可直接使用regex。

Regex 类的常用方法。

IsMatch
通过调用 IsMatch 方法确定输入文本中是否具有正则表达式模式匹配项。
Regex.IsMatch(string, pattern)
Match、Matches
通过调用 Match 或 Matches 方法检索匹配正则表达式模式的一个或所有文本匹配项。
第一个方法返回提供有关匹配文本的信息的 Match 对象。 第二个方法返回 MatchCollection 对象,该对象对于在分析的文本中找到的每个匹配项包含一个 Match 对象。
Replace
通过调用 Replace 方法替换匹配正则表达式模式的文本。
$p = New-Object System.Text.RegularExpressions.Regex('(?<=href\s*?=\s*?").*?(?=" *)') 
$p = [regex]('(?<=href\s*?=\s*?").*?(?=" *)')
$html = @"
        <nav class="navbar navbar-default">
            ......    
        </div>
"@
$r =[System.Text.RegularExpressions.Regex]::Matches($html, $p)
$r = [regex]::Matches($html, $p)
$r|ForEach-Object{$_.value}

Python 字符串替换

字符串对象提供replace 方法。
str.replace(old, new[, count])
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
re 模块提供 sub 方法,实现字符串的文本替换,sub 是 substitue 的缩写,意思是替换。
语法是:re.sub(pattern, repl, string, count=0, flags=0)
Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is, \n is converted to a single newline character, \r is converted to a carriage return, and so forth. Unknown escapes such as \& are left alone. Backreferences, such as \6, are replaced with the substring matched by group 6 in the pattern.
If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string
参考地址 re.sub

替换掉文件名在的/、\、(、)、" 符号为-。

import re

p = re.compile(r'[/\\()"]')
newFileName = re.sub(p, '_', oldFileName)

总结

正则表达式都是第三方类(库,模块)提供支持,模式字符串的字面量书写会有细微差别,JS和Python 感觉最好;类库都提供了模式匹配、查找、替换的方法,JS主要是字符串提供方法。