简体   繁体   中英

RegEx search and replace in pattern

I need to search out a pattern that can change from document to document but follows a certain pattern. The pattern will always be 9 numbers followed by 3 letters. It will sometimes have a space between them and sometimes not. Here is an example of text to search through:

  1. 009244828 FLE
  2. MID021087275
  3. 006386476JJK
  4. 002973303 JJK
  5. MNS 000110924
  6. MNS000110924
  7. 009244828PSC
  8. 001915657SCR

My current regex looks like this: .+?(?=(JJK|FLE|PSC|SCR)) . This returns lines 1,3,4,7 & 8 like this:1.

  1. 009244828\\s
  2. 006386476
  3. 002973303\\s
  4. 009244828
  5. 001915657

as it should but does not return the letters. I need to return these lines with the letters and remove the space if it is there. my returned result should look like this:

  1. 009244828FLE
  2. 006386476JJK
  3. 002973303JJK
  4. 009244828PSC
  5. 001915657SCR

Let's compose the regex you're looking for step-by-step.

What you need to match is this:

  • 9 decimal digits \\d{9}
  • An optional whitespace character \\s?
  • 3 UPPERCASE letters [AZ]{3} (use [a-zA-Z]{3} if the letters may be lowercase)

Putting it all together, this regex does almost what you want:

\d{9}\s?[A-Z]{3}

I said "almost" because it doesn't let you get rid of the space between the digits and the letters. To do that, you need to put the letters and the digits into capturing groups - after that, you can simply concatenate the captured substrings (with a replacing expression along the lines of $1$2 or \\1\\2 ) to get exactly what you want.

(\d{9})\s?([A-Z]{3})

If you want to make sure each digit-and-letter group is on its own line, simply wrap the entire regex in ^ and $ , then run it in a mode where these two characters match the beginning/end of a line instead of the beginning/end of the entire string.

^(\d{9})\s?([A-Z]{3})$

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