Get string within double quotes along with rest of the string - java

I have a case where I need to extract the string within double quotes in one var and the rest of the string in another var.
Two possibilities:
String: "Franklin B" Benjamin
Result:
var1 = Franklin B
var2 = Benjamin
String: Benjamin "Franklin B"
Result:
var1 = Benjamin
var2 = Franklin B
Regex/Without regex; I am open to any method.

Give this a try...
Basically you remove any leading delimiter in the string before you perform the split. This way you don't have to worry about a leading empty element.
public static void main(String[] args) {
String testString = "\"Franklin B\" Benjamin";
String testString2 = "Benjamin \"Franklin B\"";
displaySplitResults(mySplit(testString, "\""));
displaySplitResults(mySplit(testString2, "\""));
}
private static String[] mySplit(final String input, final String delim)
{
return input.replaceFirst("^" + delim, "").split(delim);
}
private static void displaySplitResults(String[] splitResults) {
if (splitResults.length == 2) {
String var1 = splitResults[0].trim();
String var2 = splitResults[1].trim();
System.out.println(var1);
System.out.println(var2);
}
}
Results:
Franklin B
Benjamin
Benjamin
Franklin B

A simple non-regex way to do it:
public static String[] split(String input) {
if (input.charAt(0) == '"') {
return input.substring(1).split("\" ");
} else {
return input.substring(0, input.length() - 1).split(" \"");
}
}
First check whether the first character is ". Then remove the quote from either beginning or the end and simply split it.

The following will get you a List with the values you want:
private List<String> getValues(String input) {
List<String> matchList = new ArrayList<>();
Pattern regex = Pattern.compile("[^\\s\"']+|\"[^\"]*\"|'[^']*'");
Matcher regexMatcher = regex.matcher(input);
while (regexMatcher.find()) {
matchList.add(regexMatcher.group());
}
return matchList;
}
Taken from Regex for splitting a string using space when not surrounded by single or double quotes

#Shar1er80 Nice piece of work without regex. Worked great.
I also tried with regex:
//Using regex to get values separated by whitespace but keeping values with double quotes
RegexOptions options = RegexOptions.None;
Regex regex = new Regex( #"((""((?<token>.*?)(?<!\\)"")|(?<token>[\w]+))(\s)*)", options );
string input = #" Here is ""my string"" it has "" six matches"" ";
var result = (from Match m in regex.Matches( input )
where m.Groups[ "token" ].Success
select m.Groups[ "token" ].Value).ToList();
Gave me exact result.

Related

Split a string in java into two parts

I want to split a string based on a substring, and get the first part. Example below.
Input:
body/div[2]/div[3]/div/div[1]/div/div[2]/div[2]/ul/li[12]/div/div/div/div[2]/div[2]
Ouptut: splitted at [12]
body/div[2]/div[3]/div/div[1]/div/div[2]/div[2]/ul/li[12]
I wrote this code :
String path1 = "body/div[2]/div[3]/div/div[1]/div/div[2]/div[2]/ul/li[12]/div/div/div/div[2]/div[2]"
String result;
if(path1.contains("[12]")){
System.out.println("yes");
result = path1.split("[12]")[0];
System.out.println(result);
}
but I got result like this :
body/div[
String result = path1.substring(0, path1.indexOf("li[12]") + 6);
The split method accepts regular expressions. The regular expression [12] matches one character which is either 1 or 2 and therefore splits the string between each 1 or 2. A better solution is to search for the occurrence of [12] directly:
int indexOf12 = path1.indexOf("[12]");
if(indexOf12 != -1)
{
System.out.println("yes");
String result = path1.substring(0, indexOf12 + 4);
System.out.println(result);
}
The [ character is interpreted as a special regex character so you should escape it by adding \\
So replace
result = path1.split("[12]")[0];
By
result = path1.split("\\[12]")[0];
Output:
yes
body/div[2]/div[3]/div/div[1]/div/div[2]/div[2]/ul/li
need to add [12] after substring so +6 in result
String result = path1.substring(0, path1.indexOf("li[12]")+6);
This will solve your problem. Thing is you have to provide Regex for split. Not only string.
String path1 = "body/div[2]/div[3]/div/div[1]/div/div[2]/div[2]/ul/li[12]/div/div/div/div[2]/div[2]";
String result;
if(path1.contains("[12]")){
System.out.println("yes");
result = path1.split("\\[12\\]")[0];
System.out.println(result+"[12]");
}
Here's an example of RegEx specific approach:
Matcher m = Pattern.compile("(.*\\[12\\])")
.matcher("body/div[2]/div[3]/div/div[1]/div/div[2]/div[2]/ul/li[12]/div/div/div/div[2]/div[2]");
Output
body/div[2]/div[3]/div/div[1]/div/div[2]/div[2]/ul/li[12]
Code
import java.util.regex.*;
import java.util.*;
public class HelloWorld {
public static void main(String[] args) {
List < String > allMatches = new ArrayList < String > ();
Matcher m = Pattern.compile("(.*\\[12\\])")
.matcher("body/div[2]/div[3]/div/div[1]/div/div[2]/div[2]/ul/li[12]/div/div/div/div[2]/div[2]");
while (m.find())
allMatches.add(m.group(1));
for (String match: allMatches)
System.out.println(match);
}
}

How to split a string in JAVA with two different seperators? [duplicate]

I want to split the string "004-034556" into two strings by the delimiter "-":
part1 = "004";
part2 = "034556";
That means the first string will contain the characters before '-', and the second string will contain the characters after '-'.
I also want to check if the string has '-' in it.
Use the appropriately named method String#split().
String string = "004-034556";
String[] parts = string.split("-");
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556
Note that split's argument is assumed to be a regular expression, so remember to escape special characters if necessary.
there are 12 characters with special meanings: the backslash \, the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign +, the opening parenthesis (, the closing parenthesis ), and the opening square bracket [, the opening curly brace {, These special characters are often called "metacharacters".
For instance, to split on a period/dot . (which means "any character" in regex), use either backslash \ to escape the individual special character like so split("\\."), or use character class [] to represent literal character(s) like so split("[.]"), or use Pattern#quote() to escape the entire string like so split(Pattern.quote(".")).
String[] parts = string.split(Pattern.quote(".")); // Split on the exact string.
To test beforehand if the string contains certain character(s), just use String#contains().
if (string.contains("-")) {
// Split it.
} else {
throw new IllegalArgumentException("String " + string + " does not contain -");
}
Note, this does not take a regular expression. For that, use String#matches() instead.
If you'd like to retain the split character in the resulting parts, then make use of positive lookaround. In case you want to have the split character to end up in left hand side, use positive lookbehind by prefixing ?<= group on the pattern.
String string = "004-034556";
String[] parts = string.split("(?<=-)");
String part1 = parts[0]; // 004-
String part2 = parts[1]; // 034556
In case you want to have the split character to end up in right hand side, use positive lookahead by prefixing ?= group on the pattern.
String string = "004-034556";
String[] parts = string.split("(?=-)");
String part1 = parts[0]; // 004
String part2 = parts[1]; // -034556
If you'd like to limit the number of resulting parts, then you can supply the desired number as 2nd argument of split() method.
String string = "004-034556-42";
String[] parts = string.split("-", 2);
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556-42
An alternative to processing the string directly would be to use a regular expression with capturing groups. This has the advantage that it makes it straightforward to imply more sophisticated constraints on the input. For example, the following splits the string into two parts, and ensures that both consist only of digits:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
class SplitExample
{
private static Pattern twopart = Pattern.compile("(\\d+)-(\\d+)");
public static void checkString(String s)
{
Matcher m = twopart.matcher(s);
if (m.matches()) {
System.out.println(s + " matches; first part is " + m.group(1) +
", second part is " + m.group(2) + ".");
} else {
System.out.println(s + " does not match.");
}
}
public static void main(String[] args) {
checkString("123-4567");
checkString("foo-bar");
checkString("123-");
checkString("-4567");
checkString("123-4567-890");
}
}
As the pattern is fixed in this instance, it can be compiled in advance and stored as a static member (initialised at class load time in the example). The regular expression is:
(\d+)-(\d+)
The parentheses denote the capturing groups; the string that matched that part of the regexp can be accessed by the Match.group() method, as shown. The \d matches and single decimal digit, and the + means "match one or more of the previous expression). The - has no special meaning, so just matches that character in the input. Note that you need to double-escape the backslashes when writing this as a Java string. Some other examples:
([A-Z]+)-([A-Z]+) // Each part consists of only capital letters
([^-]+)-([^-]+) // Each part consists of characters other than -
([A-Z]{2})-(\d+) // The first part is exactly two capital letters,
// the second consists of digits
Use:
String[] result = yourString.split("-");
if (result.length != 2)
throw new IllegalArgumentException("String not in correct format");
This will split your string into two parts. The first element in the array will be the part containing the stuff before the -, and the second element in the array will contain the part of your string after the -.
If the array length is not 2, then the string was not in the format: string-string.
Check out the split() method in the String class.
This:
String[] out = string.split("-");
should do the thing you want. The string class has many method to operate with a string.
// This leaves the regexes issue out of question
// But we must remember that each character in the Delimiter String is treated
// like a single delimiter
public static String[] SplitUsingTokenizer(String subject, String delimiters) {
StringTokenizer strTkn = new StringTokenizer(subject, delimiters);
ArrayList<String> arrLis = new ArrayList<String>(subject.length());
while(strTkn.hasMoreTokens())
arrLis.add(strTkn.nextToken());
return arrLis.toArray(new String[0]);
}
With Java 8:
List<String> stringList = Pattern.compile("-")
.splitAsStream("004-034556")
.collect(Collectors.toList());
stringList.forEach(s -> System.out.println(s));
Use org.apache.commons.lang.StringUtils' split method which can split strings based on the character or string you want to split.
Method signature:
public static String[] split(String str, char separatorChar);
In your case, you want to split a string when there is a "-".
You can simply do as follows:
String str = "004-034556";
String split[] = StringUtils.split(str,"-");
Output:
004
034556
Assume that if - does not exists in your string, it returns the given string, and you will not get any exception.
The requirements left room for interpretation. I recommend writing a method,
public final static String[] mySplit(final String s)
which encapsulate this function. Of course you can use String.split(..) as mentioned in the other answers for the implementation.
You should write some unit-tests for input strings and the desired results and behaviour.
Good test candidates should include:
- "0022-3333"
- "-"
- "5555-"
- "-333"
- "3344-"
- "--"
- ""
- "553535"
- "333-333-33"
- "222--222"
- "222--"
- "--4555"
With defining the according test results, you can specify the behaviour.
For example, if "-333" should return in [,333] or if it is an error.
Can "333-333-33" be separated in [333,333-33] or [333-333,33] or is it an error? And so on.
To summarize: there are at least five ways to split a string in Java:
String.split():
String[] parts ="10,20".split(",");
Pattern.compile(regexp).splitAsStream(input):
List<String> strings = Pattern.compile("\\|")
.splitAsStream("010|020202")
.collect(Collectors.toList());
StringTokenizer (legacy class):
StringTokenizer strings = new StringTokenizer("Welcome to EXPLAINJAVA.COM!", ".");
while(strings.hasMoreTokens()){
String substring = strings.nextToken();
System.out.println(substring);
}
Google Guava Splitter:
Iterable<String> result = Splitter.on(",").split("1,2,3,4");
Apache Commons StringUtils:
String[] strings = StringUtils.split("1,2,3,4", ",");
So you can choose the best option for you depending on what you need, e.g. return type (array, list, or iterable).
Here is a big overview of these methods and the most common examples (how to split by dot, slash, question mark, etc.)
You can try like this also
String concatenated_String="hi^Hello";
String split_string_array[]=concatenated_String.split("\\^");
Assuming, that
you don't really need regular expressions for your split
you happen to already use apache commons lang in your app
The easiest way is to use StringUtils#split(java.lang.String, char). That's more convenient than the one provided by Java out of the box if you don't need regular expressions. Like its manual says, it works like this:
A null input String returns null.
StringUtils.split(null, *) = null
StringUtils.split("", *) = []
StringUtils.split("a.b.c", '.') = ["a", "b", "c"]
StringUtils.split("a..b.c", '.') = ["a", "b", "c"]
StringUtils.split("a:b:c", '.') = ["a:b:c"]
StringUtils.split("a b c", ' ') = ["a", "b", "c"]
I would recommend using commong-lang, since usually it contains a lot of stuff that's usable. However, if you don't need it for anything else than doing a split, then implementing yourself or escaping the regex is a better option.
For simple use cases String.split() should do the job. If you use guava, there is also a Splitter class which allows chaining of different string operations and supports CharMatcher:
Splitter.on('-')
.trimResults()
.omitEmptyStrings()
.split(string);
The fastest way, which also consumes the least resource could be:
String s = "abc-def";
int p = s.indexOf('-');
if (p >= 0) {
String left = s.substring(0, p);
String right = s.substring(p + 1);
} else {
// s does not contain '-'
}
String Split with multiple characters using Regex
public class StringSplitTest {
public static void main(String args[]) {
String s = " ;String; String; String; String, String; String;;String;String; String; String; ;String;String;String;String";
//String[] strs = s.split("[,\\s\\;]");
String[] strs = s.split("[,\\;]");
System.out.println("Substrings length:"+strs.length);
for (int i=0; i < strs.length; i++) {
System.out.println("Str["+i+"]:"+strs[i]);
}
}
}
Output:
Substrings length:17
Str[0]:
Str[1]:String
Str[2]: String
Str[3]: String
Str[4]: String
Str[5]: String
Str[6]: String
Str[7]:
Str[8]:String
Str[9]:String
Str[10]: String
Str[11]: String
Str[12]:
Str[13]:String
Str[14]:String
Str[15]:String
Str[16]:String
But do not expect the same output across all JDK versions. I have seen one bug which exists in some JDK versions where the first null string has been ignored. This bug is not present in the latest JDK version, but it exists in some versions between JDK 1.7 late versions and 1.8 early versions.
There are only two methods you really need to consider.
Use String.split for a one-character delimiter or you don't care about performance
If performance is not an issue, or if the delimiter is a single character that is not a regular expression special character (i.e., not one of .$|()[{^?*+\) then you can use String.split.
String[] results = input.split(",");
The split method has an optimization to avoid using a regular expression if the delimeter is a single character and not in the above list. Otherwise, it has to compile a regular expression, and this is not ideal.
Use Pattern.split and precompile the pattern if using a complex delimiter and you care about performance.
If performance is an issue, and your delimiter is not one of the above, you should pre-compile a regular expression pattern which you can then reuse.
// Save this somewhere
Pattern pattern = Pattern.compile("[,;:]");
/// ... later
String[] results = pattern.split(input);
This last option still creates a new Matcher object. You can also cache this object and reset it for each input for maximum performance, but that is somewhat more complicated and not thread-safe.
You can split a string by a line break by using the following statement:
String textStr[] = yourString.split("\\r?\\n");
You can split a string by a hyphen/character by using the following statement:
String textStr[] = yourString.split("-");
public class SplitTest {
public static String[] split(String text, String delimiter) {
java.util.List<String> parts = new java.util.ArrayList<String>();
text += delimiter;
for (int i = text.indexOf(delimiter), j=0; i != -1;) {
String temp = text.substring(j,i);
if(temp.trim().length() != 0) {
parts.add(temp);
}
j = i + delimiter.length();
i = text.indexOf(delimiter,j);
}
return parts.toArray(new String[0]);
}
public static void main(String[] args) {
String str = "004-034556";
String delimiter = "-";
String result[] = split(str, delimiter);
for(String s:result)
System.out.println(s);
}
}
Please don't use StringTokenizer class as it is a legacy class that is retained for compatibility reasons, and its use is discouraged in new code. And we can make use of the split method as suggested by others as well.
String[] sampleTokens = "004-034556".split("-");
System.out.println(Arrays.toString(sampleTokens));
And as expected it will print:
[004, 034556]
In this answer I also want to point out one change that has taken place for split method in Java 8. The String#split() method makes use of Pattern.split, and now it will remove empty strings at the start of the result array. Notice this change in documentation for Java 8:
When there is a positive-width match at the beginning of the input
sequence then an empty leading substring is included at the beginning
of the resulting array. A zero-width match at the beginning however
never produces such empty leading substring.
It means for the following example:
String[] sampleTokensAgain = "004".split("");
System.out.println(Arrays.toString(sampleTokensAgain));
we will get three strings: [0, 0, 4] and not four as was the case in Java 7 and before. Also check this similar question.
One way to do this is to run through the String in a for-each loop and use the required split character.
public class StringSplitTest {
public static void main(String[] arg){
String str = "004-034556";
String split[] = str.split("-");
System.out.println("The split parts of the String are");
for(String s:split)
System.out.println(s);
}
}
Output:
The split parts of the String are:
004
034556
import java.io.*;
public class BreakString {
public static void main(String args[]) {
String string = "004-034556-1234-2341";
String[] parts = string.split("-");
for(int i=0;i<parts.length;i++) {
System.out.println(parts[i]);
}
}
}
You can use Split():
import java.io.*;
public class Splitting
{
public static void main(String args[])
{
String Str = new String("004-034556");
String[] SplittoArray = Str.split("-");
String string1 = SplittoArray[0];
String string2 = SplittoArray[1];
}
}
Else, you can use StringTokenizer:
import java.util.*;
public class Splitting
{
public static void main(String[] args)
{
StringTokenizer Str = new StringTokenizer("004-034556");
String string1 = Str.nextToken("-");
String string2 = Str.nextToken("-");
}
}
Here are two ways two achieve it.
WAY 1: As you have to split two numbers by a special character you can use regex
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TrialClass
{
public static void main(String[] args)
{
Pattern p = Pattern.compile("[0-9]+");
Matcher m = p.matcher("004-034556");
while(m.find())
{
System.out.println(m.group());
}
}
}
WAY 2: Using the string split method
public class TrialClass
{
public static void main(String[] args)
{
String temp = "004-034556";
String [] arrString = temp.split("-");
for(String splitString:arrString)
{
System.out.println(splitString);
}
}
}
You can simply use StringTokenizer to split a string in two or more parts whether there are any type of delimiters:
StringTokenizer st = new StringTokenizer("004-034556", "-");
while(st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
Check out the split() method in the String class on javadoc.
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)
String data = "004-034556-1212-232-232";
int cnt = 1;
for (String item : data.split("-")) {
System.out.println("string "+cnt+" = "+item);
cnt++;
}
Here many examples for split string but I little code optimized.
String str="004-034556"
String[] sTemp=str.split("-");// '-' is a delimiter
string1=004 // sTemp[0];
string2=034556//sTemp[1];
I just wanted to write an algorithm instead of using Java built-in functions:
public static List<String> split(String str, char c){
List<String> list = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++){
if(str.charAt(i) != c){
sb.append(str.charAt(i));
}
else{
if(sb.length() > 0){
list.add(sb.toString());
sb = new StringBuilder();
}
}
}
if(sb.length() >0){
list.add(sb.toString());
}
return list;
}
You can use the method split:
public class Demo {
public static void main(String args[]) {
String str = "004-034556";
if ((str.contains("-"))) {
String[] temp = str.split("-");
for (String part:temp) {
System.out.println(part);
}
}
else {
System.out.println(str + " does not contain \"-\".");
}
}
}
To split a string, uses String.split(regex). Review the following examples:
String data = "004-034556";
String[] output = data.split("-");
System.out.println(output[0]);
System.out.println(output[1]);
Output
004
034556
Note:
This split (regex) takes a regex as an argument. Remember to escape the regex special characters, like period/dot.
String s = "TnGeneral|DOMESTIC";
String a[]=s.split("\\|");
System.out.println(a.toString());
System.out.println(a[0]);
System.out.println(a[1]);
Output:
TnGeneral
DOMESTIC
String s="004-034556";
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)=='-')
{
System.out.println(s.substring(0,i));
System.out.println(s.substring(i+1));
}
}
As mentioned by everyone, split() is the best option which may be used in your case. An alternative method can be using substring().

How to get leading and trailing spaces in String java

In all other related posts people asked about removing leading or/and trailing spaces in String java. Now, my question is how to get the leading or trailing spaces? What I could think is for example to get the trailing spaces using such a function:
private String getTrailingSpaces(String str) {
return str.replace(str.replaceFirst("\\s+$", ""), "");
}
But I'm not sure if this is correct or even if it is, is there any better way to do this?
I'm not an expert but I think you should perform 2 distinct regexp, one for leading spaces and one for trailing spaces.
private static final Pattern LEADING = Pattern.compile("^\\s+");
private static final Pattern TRAILING = Pattern.compile("\\s+$");
public String getLeadingSpaces(String str) {
Matcher m = LEADING.matcher(str);
if(m.find()){
return m.group(0);
}
return "";
}
public String getTrailingSpaces(String str) {
Matcher m = TRAILING.matcher(str);
if(m.find()){
return m.group(0);
}
return "";
}
try this
String leading = str.replaceAll("^(\\s+).+", "$1");
String tailing = str.replaceAll(".+?(\\s+)$", "$1");
Try something like this:
private String getTrailingSpaces(String str) {
Pattern p = Pattern.compile(".*(\\s+)$");
Matcher m = p.matcher(str);
String trailing = "";
if (m.matches) {
trailing = m.group(1);
}
return trailing;
}
Try this.You would need ArrayUtils from Apache Commons though.
String str1 = " abc ";
char[] cs = str1.toCharArray();
Character[] characters = ArrayUtils.toObject(cs);
// System.out.println(characters.length); // 6
for (Character character : characters) {
if (character.isSpace(character.charValue())) {
// PROCESS ACCORDINGLY
} else {
// PROCESS ACCORDINGLY
}
}

Split Java String

Title seems to be simple. But I don't get a good Idea. This is the situation
I have String like this in my Java program
String scz="3282E81WHT-22/24";
I want to split the above string into 3 Strings, such that
first string value should be 3282e81,
Next string should be WHT(ie, the String part of above string and this part is Always of 3 Characters ),
Next String value should be 22/24 (Which will always occur after -)
In short
String first= /* do some expression on scz And value should be "3282e81" */;
String second= /* do some expression on scz And value should be "WHT" */;
String third= /* do some expression on scz And value should be "22/24" */;
Input can also be like
scz="324P25BLK-12";
So 324P25 will be first String, BLK will be second (of 3 Characters). 12 will be third ( After - symbol )
How to solve this?
You can use a regex like this (\d+[A-Z]\d+)([A-Z]+)-([/\d]+) and using Matcher.group(int) method you can get your string splitted into three groups.
Code snippet
String str = "3282E81WHT-22/24";
//str = "324P25BLK-12";
Pattern pattern = Pattern.compile("(\\d+[A-Z]\\d+)([A-Z]+)-([/\\d]+)");
Matcher match = pattern.matcher(str);
System.out.println(match.matches());
System.out.println(match.group(1));
System.out.println(match.group(2));
System.out.println(match.group(3));
Output
true
3282E81
WHT
22/24
Use this to split the entire string in to two
String[] parts = issueField.split("-");
String first = parts[0];
String second= parts[1];
Use this to split the first string into two
if (first!=null && first.length()>=3){
String lastThree=first.substring(first.length()-3);
}
if your String's Second part (WHT) etc will always be of 3 Characters then following code will surely help you
String scz = "3282E81WHT-22/24";
String Third[] = scz.split("-");
String rev = new StringBuilder(Third[0]).reverse().toString();
String Second=rev.substring(0,3);
String First=rev.substring(3,rev.length());
// here Reverse your String Back to Original
First=new StringBuilder(First).reverse().toString();
Second=new StringBuilder(Second).reverse().toString();
System.out.println(First + " " + Second + " " + Third[1]);
You can use subString() method to get this goals.
subString has numbers of overloads.
for first string
String first=scz.subString(0,6);
String second=scz.subString(7,9);
You can use following regex to take out the above type string:
\d+[A-Z]\d{2}|[A-Z]{3}|(?<=-)[\d/]+
In Java, you can use above regex in following way:
Pattern pattern = Pattern.compile("\\d+[A-Z]\\d{2}|[A-Z]{3}|(?<=-)[\\d/]+");
Matcher matcher = pattern.matcher("3282E81WHT-22/24");
while (matcher.find()) {
System.out.println(matcher.group());
}
Output:
3282E81
WHT
22/24
You could us a char array instead of a string so you can access specific characters withing the array.
Example
char scz[] = "3282E81WHT-22/24";
and access the separate characters just by specifying the place in which the array you want to use.
You can try this
String scz="3282E81WHT-22/24";
String[] arr=scz.split("-");
System.out.println("first: "+arr[0].substring(0,7));
System.out.println("second: "+arr[0].substring(7,10));
System.out.println("third: "+arr[1])
Check out my solution -
class Main {
public static void main(String[] args) {
String first = "";
String second = "";
String third = "";
String scz="3282E81WHT-22/24";
String[] portions = scz.split("-");
if (portions.length > 1) {
third = portions[1];
}
String[] anotherPortions = portions[0].split("[a-zA-Z]+$");
if (anotherPortions.length > 0) {
first = anotherPortions[0];
}
second = portions[0].substring(first.length());
System.out.println(first);
System.out.println(second);
System.out.println(third);
}
}
Live Demo.
String scz="3282E81WHT-22/24";
String[] array = scz.split("-");
String str1 = (String) array[0].subSequence(0, 7);
String str2 = array[0].substring(7);
Then the split will be in this order :)
str1
str2
array[1]
if the length of string is fixed for scz, first,second and third the you can use
String first=scz.subString(0,6);
String second=scz.subString(7,9);
String third=scz.subString(10,scz.length());

java replaceLast() [duplicate]

This question already has answers here:
Replace the last part of a string
(11 answers)
Closed 5 years ago.
Is there replaceLast() in Java? I saw there is replaceFirst().
EDIT: If there is not in the SDK, what would be a good implementation?
It could (of course) be done with regex:
public class Test {
public static String replaceLast(String text, String regex, String replacement) {
return text.replaceFirst("(?s)"+regex+"(?!.*?"+regex+")", replacement);
}
public static void main(String[] args) {
System.out.println(replaceLast("foo AB bar AB done", "AB", "--"));
}
}
although a bit cpu-cycle-hungry with the look-aheads, but that will only be an issue when working with very large strings (and many occurrences of the regex being searched for).
A short explanation (in case of the regex being AB):
(?s) # enable dot-all option
A # match the character 'A'
B # match the character 'B'
(?! # start negative look ahead
.*? # match any character and repeat it zero or more times, reluctantly
A # match the character 'A'
B # match the character 'B'
) # end negative look ahead
EDIT
Sorry to wake up an old post. But this is only for non-overlapping instances.
For example .replaceLast("aaabbb", "bb", "xx"); returns "aaaxxb", not "aaabxx"
True, that could be fixed as follows:
public class Test {
public static String replaceLast(String text, String regex, String replacement) {
return text.replaceFirst("(?s)(.*)" + regex, "$1" + replacement);
}
public static void main(String[] args) {
System.out.println(replaceLast("aaabbb", "bb", "xx"));
}
}
If you don't need regex, here's a substring alternative.
public static String replaceLast(String string, String toReplace, String replacement) {
int pos = string.lastIndexOf(toReplace);
if (pos > -1) {
return string.substring(0, pos)
+ replacement
+ string.substring(pos + toReplace.length());
} else {
return string;
}
}
Testcase:
public static void main(String[] args) throws Exception {
System.out.println(replaceLast("foobarfoobar", "foo", "bar")); // foobarbarbar
System.out.println(replaceLast("foobarbarbar", "foo", "bar")); // barbarbarbar
System.out.println(replaceLast("foobarfoobar", "faa", "bar")); // foobarfoobar
}
use replaceAll and add a dollar sign right after your pattern:
replaceAll("pattern$", replacement);
You can combine StringUtils.reverse() with String.replaceFirst()
See for yourself: String
Or is your question actually "How do I implement a replaceLast()?"
Let me attempt an implementation (this should behave pretty much like replaceFirst(), so it should support regexes and backreferences in the replacement String):
public static String replaceLast(String input, String regex, String replacement) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
if (!matcher.find()) {
return input;
}
int lastMatchStart=0;
do {
lastMatchStart=matcher.start();
} while (matcher.find());
matcher.find(lastMatchStart);
StringBuffer sb = new StringBuffer(input.length());
matcher.appendReplacement(sb, replacement);
matcher.appendTail(sb);
return sb.toString();
}
Use StringUtils from apache:
org.apache.commons.lang.StringUtils.chomp(value, ignoreChar);
No.
You could do reverse / replaceFirst / reverse, but it's a bit expensive.
If the inspected string is so that
myString.endsWith(substringToReplace) == true
you also can do
myString=myString.replaceFirst("(.*)"+myEnd+"$","$1"+replacement)
it is slow, but works:3
import org.apache.commons.lang.StringUtils;
public static String replaceLast(String str, String oldValue, String newValue) {
str = StringUtils.reverse(str);
str = str.replaceFirst(StringUtils.reverse(oldValue), StringUtils.reverse(newValue));
str = StringUtils.reverse(str);
return str;
}
split the haystack by your needle using a lookahead regex and replace the last element of the array, then join them back together :D
String haystack = "haystack haystack haystack";
String lookFor = "hay";
String replaceWith = "wood";
String[] matches = haystack.split("(?=" + lookFor + ")");
matches[matches.length - 1] = matches[matches.length - 1].replace(lookFor, replaceWith);
String brandNew = StringUtils.join(matches);
I also have encountered such a problem, but I use this method:
public static String replaceLast2(String text,String regex,String replacement){
int i = text.length();
int j = regex.length();
if(i<j){
return text;
}
while (i>j&&!(text.substring(i-j, i).equals(regex))) {
i--;
}
if(i<=j&&!(text.substring(i-j, i).equals(regex))){
return text;
}
StringBuilder sb = new StringBuilder();
sb.append(text.substring(0, i-j));
sb.append(replacement);
sb.append(text.substring(i));
return sb.toString();
}
It really works good. Just add your string where u want to replace string in s and in place of "he" place the sub string u want to replace and in place of "mt" place the sub string you want in your new string.
import java.util.Scanner;
public class FindSubStr
{
public static void main(String str[])
{
Scanner on=new Scanner(System.in);
String s=on.nextLine().toLowerCase();
String st1=s.substring(0, s.lastIndexOf("he"));
String st2=s.substring(s.lastIndexOf("he"));
String n=st2.replace("he","mt");
System.out.println(st1+n);
}
}

Categories