Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
525 views
in Technique[技术] by (71.8m points)

ms word - Regex code for any string containing BOTH letters AND digits and possibly underscores and dashes

My regex knowledge is pretty limited, but I'm trying to write/find an expression that will capture the following string types in a document:

DO match:

  • ADY123
  • AD12ADY
  • 1HGER_2
  • 145-DE-FR2
  • Bicycle1
  • 2Bicycle
  • 128D
  • 128878P

DON'T match:

  • BICYCLE
  • 183-329-193
  • 3123123

Is such an expression possible? Basically, it should find any string containing letters AND digits, regardless of whether the string contains a dash or underscore. I can find the first two using the following two regex:

  • /([A-Z][0-9])w+/g
  • /([0-9][A-Z)w+/g

But searching for possible dashes and hyphens makes it more complicated...

Thanks for any help you can provide! :)

MORE INFO:

I've made slight progress with: ([A-Z|a-z][0-9]+-*_*w+) but it doesn't capture strings with more than one hyphen.

I had a document with a lot of text strings and number strings, which I don't want to capture. What I do want is any product code, which could be any length string with or without hyphens and underscores but will always include at least one digit and at least one letter.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the following expression with the case-insensitive mode:

((?:[a-z]+S*d+|dS*[a-z]+)[a-zd_-]*)

Explanation:

                   # Assert position at a word boundary
(                    # Beginning of capturing group 1
  (?:                # Beginning of the non-capturing group
    [a-z]+S*d+     # Match letters followed by numbers
    |                # OR
    d+S*[a-z]+     # Match numbers followed by letters
  )                  # End of the group
  [a-zd_-]*         # Match letter, digit, '_', or '-' 0 or more times
)                    # End of capturing group 1
                   # Assert position at a word boundary

Regex101 Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...