简体   繁体   中英

Regex words with letters, numbers, optional special characters in any order

I've been using some help on here for a while now but cannot find anything specific to my requirement. I need to pick out whole words which contain at least 6 letters and/or numbers (combined, not each), with optional 'special' characters. All in any order, so A12345 , 12345A , 1-2-345-A , 12A45B and so-on.

I've done a fiddle here . I'm almost there (but could be done better) - I can't work out why it needs to be a least 6 numbers to get a match. Is it beacuse the letters are all optional with *

This is VBA so no access to look behinds. The special characters will only ever be 'within' the match, not start or end (will never be -1234-A- for example).

I think this is what you are looking for:

[a-z0-9/-]{6,}

That will match in any order a to z or 0 to 9 or - or / of at least 6. Note the - is at the end of the character class. You can have it in the middle but then need to escape it. Also, / will need to be escaped if your delimiters are also /

update

As Wiktor noted this would also capture ------ which may not be what you want. I would suggest simply cleaning out all optional characters, and then running the above regex. I would delete my answer since I'm not providing exactly what was being asked, but it would be a workable solution so it may have value.

You could do a regex replacement to remove all non letters/numbers, and then check that the length of the resulting string is 6 or more:

Dim input As String = "A-1234-B"
Dim pattern As String = "[^A-Za-z0-9]+"
Dim replacement As String = ""
Dim rgx As New Regex(pattern)
Dim result As String = rgx.Replace(input, replacement)

Console.WriteLine(result.Length)   ' 6

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM