简体   繁体   中英

How do i extract a string containing digits and characters, using regex in java

I have variable data and i want to extract a String (containing digits and characters) that is 6 characters long.

Sample_data = YOUR SET ADDRESS IS 6B1BC0 TSTSB NFPSNC92

Sample_data2 = YOUR SET ADDRESS IS 3EC810 P-22A LS02 STA-0213 TSTSA

All Strings of my sample data are variable except "YOUR SET ADDRESS IS"

I need to extract this 6 character long string: "6B1BC0" & "3EC810"

This is what i have tried do far but it isn't returning anything. How do i modify this to return "6B1BC0"

Pattern P = pattern.compile(“YOUR SET ADDRESS IS \\w+ ([A-Z0-9]{6})”);
Matcher n = p.matcher(result);
If(n.find())
{
    return n.group(0);
}
Pattern P = pattern.compile(“YOUR SET ADDRESS IS\\s+([A-Z0-9]{6})”);

关于"YOUR SET ADDRESS IS ( [A-Z0-9]{6})*"

You're almost there. Fix your pattern to:

Pattern P = pattern.compile("YOUR SET ADDRESS IS ([A-Z0-9]{6})");

or

Pattern P = pattern.compile("YOUR SET ADDRESS IS\\s+([A-Z0-9]{6})");

Working program:

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.*;

class Test
{
  public static void main (String[] args) throws java.lang.Exception
  {
    Pattern p = Pattern.compile("YOUR SET ADDRESS IS\\s+([A-Z0-9]{6})");
    Matcher n = p.matcher("YOUR SET ADDRESS IS 123456 FOO");
    if (n.find()) {
      System.out.println(n.group(1)); // Prints 123456
    }
  }
}
Pattern p = Pattern.compile("^[a-zA-Z]+([0-9]+).*");
Matcher m = p.matcher("aTesting123anythingTesting");

if (m.find()) {
    System.out.println(m.group(1));
}

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