gpt4 book ai didi

javascript - 正则表达式字符串最多包含 1 个 '#'

转载 作者:行者123 更新时间:2023-11-28 13:40:01 27 4
gpt4 key购买 nike

需要正则表达式通过模式匹配字符串,排除字符串中“#”超过 1 次的情况

var srg = new RegExp(/([a-z0-9#]+[\s])/g);

字符串:

fdsffmsd,fmsd 
qwjswkds03sj
ewew
rfekwjkr#jfkdlsf
wiru0ksd#erjk#jkls
#
casdw##kfdl

结果

fdsffmsd,fmsd

qwjswkds03sj

哎呀

rfekwjkr#jfkdlsf

wiru0ksd#erjk#jkls

#

casdw##kfdl

Fiddle

谢谢

更新:

请原谅我的任务解释不太好

我更新了新的 fiddle New fiddle

var srg = new RegExp(/((\-)[a-z0-9#]+[\s])/g);

我们做什么:

  • 搜索“-”字符

  • 如果找到 - 匹配 a-z0-9# 但不满足任何空格

  • 需要添加条件,仅在模式捕获中匹配 # 0 或 1 次

可能类似于 [a-z0-9#{0,1}] 表示 # 0 次或一次...

最佳答案

描述

这个表达式将:

  • 要求字符串以 - 字符开头
  • 允许#在字符串中最多出现1次
  • 防止字符串中出现空格
  • 允许使用一个或多个 a-z0-9 字符
  • 允许#字符出现在字符串中的任何位置,包括开头和结尾

^(?!(?:.*?#){2,})-[a-z0-9#]+$

enter image description here

NODE                     EXPLANATION
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
(?! look ahead to see if there is not:
--------------------------------------------------------------------------------
(?: group, but do not capture (at least 2
times (matching the most amount
possible)):
--------------------------------------------------------------------------------
.*? any character except \n (0 or more
times (matching the least amount
possible))
--------------------------------------------------------------------------------
# '#'
--------------------------------------------------------------------------------
){2,} end of grouping
--------------------------------------------------------------------------------
) end of look-ahead
--------------------------------------------------------------------------------
- '-'
--------------------------------------------------------------------------------
[a-z0-9#]+ any character of: 'a' to 'z', '0' to '9',
'#' (1 or more times (matching the most
amount possible))
--------------------------------------------------------------------------------
$ before an optional \n, and the end of the
string

示例

Live Demo

示例

-abcdefghijklmnopqrstuvwxyz1234567890     = good
-abcdefghijklmnopq#rstuvwxyz1234567890 = good
-abcdefghijklmnopq##rstuvwxyz1234567890 = bad
-#abcdefghijklmnopqrstuvwxyz1234567890 = good
-##abcdefghijklmnopqrstuvwxyz1234567890 = bad
-#abcdefghijklmnopqrstuvwxyz1234567890 = good
-abcdefghijklmnopqrstuvwxyz1234567890# = good
-#abcdefghijklmnopqrstuvwxyz1234567890# = bad
#-abcdefghijklmnopqrstuvwxyz1234567890 = bad

关于javascript - 正则表达式字符串最多包含 1 个 '#',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18463211/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com