我如何使一个表达式匹配绝对任何东西(包括空白)?例子:
Regex:我买了_____羊。
火柴:我买了羊。我买了一只羊。我买了五只羊。
我尝试使用(.*),但似乎没有工作。
我如何使一个表达式匹配绝对任何东西(包括空白)?例子:
Regex:我买了_____羊。
火柴:我买了羊。我买了一只羊。我买了五只羊。
我尝试使用(.*),但似乎没有工作。
当前回答
如果你使用JavaScript, ES2018添加了/s (dotAll)标志。带有/s标志的点。将匹配任何字符,包括换行符。
游戏机log(“line_1 \ nline_2”。match (/ + / s))
注意:目前还不是所有浏览器都支持它。
其他回答
/。如果没有换行符,*/效果很好。如果它必须匹配换行符,这里有一些解决方案:
Solution | Description |
---|---|
/.*/s |
/s (dot all flag) makes . (wildcard character) match anything, including line breaks. Throw in an * (asterisk), and it will match everything. Read more. |
/[\s\S]*/ |
\s (whitespace metacharacter) will match any whitespace character (space; tab; line break; ...), and \S (opposite of \s ) will match anything that is not a whitespace character. * (asterisk) will match all occurrences of the character set (Encapsulated by [] ). Read more. |
Regex: /I bought.*sheep./ Matches - the whole string till the end of line I bought sheep. I bought a sheep. I bought five sheep. Regex: /I bought(.*)sheep./ Matches - the whole string and also capture the sub string within () for further use I bought sheep. I bought a sheep. I bought five sheep. I boughtsheep. I bought a sheep. I bought fivesheep. Example using Javascript/Regex 'I bought sheep. I bought a sheep. I bought five sheep.'.match(/I bought(.*)sheep./)[0]; Output: "I bought sheep. I bought a sheep. I bought five sheep." 'I bought sheep. I bought a sheep. I bought five sheep.'.match(/I bought(.*)sheep./)[1]; Output: " sheep. I bought a sheep. I bought five "
我用这个:(.|\n)+对我来说就像一个魅力!
如果你使用JavaScript, ES2018添加了/s (dotAll)标志。带有/s标志的点。将匹配任何字符,包括换行符。
游戏机log(“line_1 \ nline_2”。match (/ + / s))
注意:目前还不是所有浏览器都支持它。
使用.*,并确保您使用的实现相当于单行,以便在行尾匹配。
这里有一个很好的解释-> http://www.regular-expressions.info/dot.html