本文翻译自: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 . - 分号 。
I wrote this: 我写了这个:
/^(.*);/
But it actually matches everything (including the semicolon) until the last occurrence of a semicolon. 但它实际上匹配所有内容(包括分号),直到最后一次出现分号。
#1楼
参考:https://stackoom.com/question/8Rhk/正则表达式-匹配第一次出现的字符
#2楼
"/^([^\\/]*)\\/$/"
worked for me, to get only top "folders" from an array like: "/^([^\\/]*)\\/$/"
对我有用,只能从数组中获取顶级“文件夹”:
a/ <- this
a/b/
c/ <- this
c/d/
/d/e/
f/ <- this
#3楼
Try /[^;]*/
试试/[^;]*/
Google regex character classes
for details. 谷歌regex character classes
的详细信息。
#4楼
/^[^;]*/
The [^;] says match anything except a semicolon. [^;]表示匹配除分号之外的任何内容。 The square brackets are a set matching operator, it's essentially, match any character in this set of characters, the ^
at the start makes it an inverse match, so match anything not in this set. 方括号是一个集合匹配运算符,它本质上匹配这组字符中的任何字符,开头的^
使它成为反向匹配,因此匹配不在此集合中的任何内容。
#5楼
Try /[^;]*/
试试/[^;]*/
That's a negating character class . 这是一个否定的角色类 。
#6楼
You need 你需要
/[^;]*/
The [^;]
is a character class , it matches everything but a semicolon. [^;]
是一个字符类 ,它匹配除分号之外的所有内容。
To cite the perlre
manpage: 引用perlre
页:
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. 这适用于大多数正则表达式方言。