正则表达式:匹配第一次出现的字符

本文翻译自: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. 这适用于大多数正则表达式方言。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值