正则表达式:匹配到第一次出现的字符 [英] Regex: matching up to the first occurrence of a character
问题描述
我正在寻找一种匹配所有直到特定字符第一次出现的模式,比如;"- 分号.
I am looking for a pattern that matches everything until the first occurrence of a specific character, say a ";" - a semicolon.
我是这样写的:
/^(.*);/
但它实际上匹配所有内容(包括分号),直到最后一次出现分号.
But it actually matches everything (including the semicolon) until the last occurrence of a semicolon.
推荐答案
您需要
/[^;]*/
[^;]
是一个字符类,它匹配除分号之外的所有内容.
The [^;]
is a character class, it matches everything but a semicolon.
引用 perlre
手册页:
To cite the perlre
manpage:
您可以通过在 [] 中包含一个字符列表来指定一个字符类,该列表将匹配列表中的任何字符.如果["后的第一个字符是^",则该类匹配不在列表中的任何字符.
You can specify a character class, by enclosing a list of characters in [] , which will match any character from the list. If the first character after the "[" is "^", the class matches any character not in the list.
这应该适用于大多数正则表达式方言.
This should work in most regex dialects.
这篇关于正则表达式:匹配到第一次出现的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!