Regex忽略贪婪的特殊字符



我使用以下正则表达式捕获了10个数字和字母:

/[a-zA-Z0-9]{10}/g

如果这10个字符只是数字和字母,则效果良好。

例如输入:12345xcdw034342
它捕获12345xcdw0

但在这种有特殊字符或空格的情况下,它不会捕获它。
123}456712234324Zz3123}45 71223AB3

它应该捕获10个数字和字母,而不是字符。

如有任何帮助,我们将不胜感激。

你可以这样做,但不需要任何额外的处理

由于您还没有具体说明您使用的是什么语言,我将使用Javascript,因为它非常通用,但相同的逻辑必须适用于任何语言。

以下是我能想到的选项

如果我有testString = "12@34{56A789BDE"

  1. 将所有字符匹配到前十个字母数字字符,然后删除结果字符串中的特殊字符
testString.match(/(w.*?){10}/)[0].replaceAll(/W/g, '')
// results '123456A789'
// explanation: we take the first w and use .*? to indicate that we dont care if the alphanumeric has a non-alphanumeric right next to it, then we clean the result by removing W which means non-alphanumeric 
  1. 只匹配前十个字母数字字符,然后将它们连接成结果字符串
testString.match(/w/g).splice(0,10).join('')
// results '123456A789'
// explanation: we match 10 groups of aphanumeric characters represented by  w (note the lowercase) and we join the first 10 (using splice to get them) as each group "()" is in the case of javascript returned as an element of an array of matches
  1. 从字符串中删除特殊字符,然后取前十个
testString.replaceAll(/W/g,'').match(/w{10}/)[0]
// results '123456A789'
// explanation:  we replace W which means non alpha numeric characters, with '' to delete them then we match the first ten

您可以使用

/[a-zA-Z0-9](?:[^a-zA-Z0-9]*[a-zA-Z0-9]){9}/g

请参阅regex演示详细信息

  • [a-zA-Z0-9]-字母数字
  • (?:[^a-zA-Z0-9]*[a-zA-Z0-9]){9}-除字母数字字符和字母数字字符外,任何零个或多个字符出现九次

最新更新