简体   繁体   中英

Splitting a string composed of numbers and alphabets

I want to break a string like :

String s = "xyz213123kop234430099kpf4532";

into tokens where each token starts with an alphabet and ends with a number. So the above string can be broken down into 3 tokens :

xyz213123
kop234430099
kpf4532

This string s could be very big but the pattern will remain the same, ie each token will start with 3 alphabets and end with a number.

How do I split them ?

Try this:

\w+?\d+

Java Matcher :

Pattern pattern = Pattern.compile("\\w+?\\d+"); //compiles the pattern we want to use
Matcher matcher = pattern.matcher("xyz213123kop234430099kpf4532"); //we create the matcher on certain string using our pattern

while(matcher.find()) //while the matcher can find the next match
{
    System.out.println(matcher.group()); //print it
}

And then you could use Regex.Matches C#:

foreach(Match m in Regex.Matches("xyz213123kop234430099kpf4532", @"\w+?\d+"))
{
    Console.WriteLine(m.Value);
}

And for the future this:

RegExr

Do it like this,

String s = "xyz213123kop234430099kpf4532";

    Pattern p = Pattern.compile("\\w+?\\d+");
    Matcher match = p.matcher(s);
    while(match.find()){
        System.out.println(match.group());  
    }

OUTPUT

xyz213123
kop234430099
kpf4532

您可以从这样的正则表达式开始:(\\ w +?\\ d +) http://regexr.com?36utt

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