Home  >  Article  >  Computer Tutorials  >  Java method to extract string prefix

Java method to extract string prefix

PHPz
PHPzforward
2024-01-16 11:42:19501browse

Java method to extract string prefix

Help write a java method to extract the first participle of String

public class SubString {

//Class for processing strings

public static String getString(String src, String target) {

//Get the content before the last occurrence of target in the source string src

return src.substring(0, src.lastIndexOf(target));

}

//For testing

public static void main(String[] args) {

// TODO Auto-generated method stub

String target = "Department"; //Set target to "Department"

//Get the required string

String result = getString("Commissary", target); //For the sake of harmony..

System.err.println(result);

}

}

Output result:

小selling

This method is also applicable to multiple words, such as management department. When the target is set to "department", the running result of the program will be "management"

How does Java use regular expressions to complete the following tasks: truncate strings starting with letters or numbers

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class ttts {

public static void main(String... strs) {

String str = "VVV4BC3233BBB";

System.out.println(getStrings(new StringBuilder(),str));

}

public static String getStrings(StringBuilder sb,String str) {

if (str == null)return """;

if (str.equals("""))return sb.toString();

Pattern p = Pattern.compile("[a-zA-Z]*[0-9]*");

Matcher m = p.matcher(str);

if (m.find()) {

String group = m.group();

sb.append(group);

String subStr = str.substring(group.length());

Pattern pattern = Pattern.compile(".*\\d .*");

if (pattern.matcher(subStr).matches()) {

getStrings(sb,str.substring(group.length()));

}

}

return sb.toString();

}

}

The above is the detailed content of Java method to extract string prefix. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:docexcel.net. If there is any infringement, please contact admin@php.cn delete