Replace word from string in java - java

String[] operatorList = { "name", "first_name", "last_name", "city" };
String originalString = "city=Houston^ORlast_name=Cervantsz^ORfirst_name=John^name=don";
for (String opElement : operatorList) {
if (originalString.contains(opElement)) {
String tempStr = originalString.replace(opElement, "user." + opElement);
originalString = tempStr;
}
}
System.out.println("originalString " + originalString);
Output:
user.city=Houston^ORlast_user.name=Cervantsz^ORfirst_user.name=John^user.name=don
When i am trying to replace name with "user.name" at that time name from "last_name" is replaced with "last_user.name" and first_name with first_user.name
But i want replace "name" with "user.name" and "last_name" with "user.last_name"
and "first_name" with "user.first_name".
Any help appreciated.

You can add prefix all key and control that key. Example
String[] operatorList = {"name", "first_name", "last_name", "city"};
String originalString = "city=Houston^ORlast_name=Cervantsz^ORfirst_name=John^ORname=don";
for (String opElement : operatorList) {
if (originalString.contains("^OR"+opElement)) {
String tempStr = originalString.replace(opElement, "user." + opElement);
originalString = tempStr;
}
}
System.out.println("originalString " + originalString);

If the values you are trying to change are always unique and generated (meaning they are always in the same order), you can simply put your operators in the same order and use replaceLast() instead.
A more complete solution would be to determine how the string is constructed. Do all the values have a ^ in front of them? Is OR generated for the same values or is it to indicate optional values?. So in the end, what allows you to split the string properly. Then you can use a Regex to use the surrounding characters.
I would format the string to make sure the splitters are constant (all "^OR" become "##%!!" and all remaining "^" become "%!!") so all replaced strings start with !!. Then I would reformat the string to the original format using the remaining "##%" or "%" :
String[] operatorList = { "name", "first_name", "last_name", "city" };
String originalString = "city=Houston^ORlast_name=Cervantsz^ORfirst_name=John^name=don";
originalString = originalString.replaceAll("\\^OR", "##%!!");
originalString = originalString.replaceAll("\\^", "%!!");
//the order is important here
for (String opElement : operatorList) {
if (originalString.startsWith(opElement)) {
originalString = originalString.replaceFirst(opElement, "user." + opElement);
}
originalString = originalString.replaceAll("!!" + opElement, "user." + opElement);
// no need for an other alternative here because replaceAll returns the
// String as is if it does not find the first parameter in the String.
}
originalString = originalString.replaceAll("##%", "^OR");
originalString = originalString.replaceAll("%", "^");
// the order here is also important
outputs : "user.city=Houston^ORuser.last_name=Cervantsz^ORuser.first_name=John^user.name=don"

If all keypairs need prefix "user.", I would like to split originalString first.
In Java8
String originalString = "city=Houston^ORlast_name=Cervantsz^ORfirst_name=John^name=don";
String[] params = originalString.split("\\^");
String result = String.join("^", Arrays.stream(params)
.map(param -> param.startsWith("OR") ? "ORuser." + param.substring(2) : "user." + param)
.collect(Collectors.toList()));
System.out.println(result);
It can also be changed to for loop type.

You may use a quick search and replace with an alternation based pattern created dynamically from the search words only when they are preceded with a word boundary or ^ + OR/AND/etc. operators and followed with a word boundary. Note that this solution assumes the search words only consist of word chars (letters, digits or _):
String[] operatorList = { "name", "first_name", "last_name", "city" };
// assuming operators only consist of word chars
String pat = "(\\b|\\^(?:OR|AND)?)(" + String.join("|", operatorList) + ")\\b";
String originalString = "city=Houston^ORlast_name=Cervantsz^ORfirst_name=John^name=don";
originalString = originalString.replaceAll(pat, "$1user.$2");
System.out.println(originalString);
// => user.city=Houston^ORuser.last_name=Cervantsz^ORuser.first_name=John^user.name=don
See the Java demo online
The regex will look like
(\b|\^(?:OR|AND)?)(name|first_name|last_name|city)\b
See the regex demo.
Details
(\b|\^(?:OR|AND)?) - Group 1: a word boundary \b or a ^ symbol and an optional substring, OR or AND (you may add more here after |)
(name|first_name|last_name|city) - Group 2: any of the search words
\b - a trailing word boundary.
The $1 in the replacement pattern inserts the contents of Group 1 and $2 does the same with Group 2 contents.

Related

Remove parts of String? [duplicate]

I want to remove a part of string from one character, that is:
Source string:
manchester united (with nice players)
Target string:
manchester united
There are multiple ways to do it. If you have the string which you want to replace you can use the replace or replaceAll methods of the String class. If you are looking to replace a substring you can get the substring using the substring API.
For example
String str = "manchester united (with nice players)";
System.out.println(str.replace("(with nice players)", ""));
int index = str.indexOf("(");
System.out.println(str.substring(0, index));
To replace content within "()" you can use:
int startIndex = str.indexOf("(");
int endIndex = str.indexOf(")");
String replacement = "I AM JUST A REPLACEMENT";
String toBeReplaced = str.substring(startIndex + 1, endIndex);
System.out.println(str.replace(toBeReplaced, replacement));
String Replace
String s = "manchester united (with nice players)";
s = s.replace(" (with nice players)", "");
Edit:
By Index
s = s.substring(0, s.indexOf("(") - 1);
Use String.Replace():
http://www.daniweb.com/software-development/java/threads/73139
Example:
String original = "manchester united (with nice players)";
String newString = original.replace(" (with nice players)","");
originalString.replaceFirst("[(].*?[)]", "");
https://ideone.com/jsZhSC
replaceFirst() can be replaced by replaceAll()
Using StringBuilder, you can replace the following way.
StringBuilder str = new StringBuilder("manchester united (with nice players)");
int startIdx = str.indexOf("(");
int endIdx = str.indexOf(")");
str.replace(++startIdx, endIdx, "");
You should use the substring() method of String object.
Here is an example code:
Assumption: I am assuming here that you want to retrieve the string till the first parenthesis
String strTest = "manchester united(with nice players)";
/*Get the substring from the original string, with starting index 0, and ending index as position of th first parenthesis - 1 */
String strSub = strTest.subString(0,strTest.getIndex("(")-1);
I would at first split the original string into an array of String with a token " (" and the String at position 0 of the output array is what you would like to have.
String[] output = originalString.split(" (");
String result = output[0];
Using StringUtils from commons lang
A null source string will return null. An empty ("") source string will return the empty string. A null remove string will return the source string. An empty ("") remove string will return the source string.
String str = StringUtils.remove("Test remove", "remove");
System.out.println(str);
//result will be "Test"
If you just need to remove everything after the "(", try this. Does nothing if no parentheses.
StringUtils.substringBefore(str, "(");
If there may be content after the end parentheses, try this.
String toRemove = StringUtils.substringBetween(str, "(", ")");
String result = StringUtils.remove(str, "(" + toRemove + ")");
To remove end spaces, use str.trim()
Apache StringUtils functions are null-, empty-, and no match- safe
Kotlin Solution
If you are removing a specific string from the end, use removeSuffix (Documentation)
var text = "one(two"
text = text.removeSuffix("(two") // "one"
If the suffix does not exist in the string, it just returns the original
var text = "one(three"
text = text.removeSuffix("(two") // "one(three"
If you want to remove after a character, use
// Each results in "one"
text = text.replaceAfter("(", "").dropLast(1) // You should check char is present before `dropLast`
// or
text = text.removeRange(text.indexOf("("), text.length)
// or
text = text.replaceRange(text.indexOf("("), text.length, "")
You can also check out removePrefix, removeRange, removeSurrounding, and replaceAfterLast which are similar
The Full List is here: (Documentation)
// Java program to remove a substring from a string
public class RemoveSubString {
public static void main(String[] args) {
String master = "1,2,3,4,5";
String to_remove="3,";
String new_string = master.replace(to_remove, "");
// the above line replaces the t_remove string with blank string in master
System.out.println(master);
System.out.println(new_string);
}
}
You could use replace to fix your string. The following will return everything before a "(" and also strip all leading and trailing whitespace. If the string starts with a "(" it will just leave it as is.
str = "manchester united (with nice players)"
matched = str.match(/.*(?=\()/)
str.replace(matched[0].strip) if matched

How to search word in String text, this word end "." or "," in java

someone can help me with code?
How to search word in String text, this word end "." or "," in java
I don't want search like this to find it
String word = "test.";
String wordSerch = "I trying to tasting the Artestem test.";
String word1 = "test,"; // here with ","
String word2 = "test."; // here with "."
String word3 = "test"; //here without
//after i make string array and etc...
if((wordSearch.equalsIgnoreCase(word1))||
(wordSearch.equalsIgnoreCase(word2))||
(wordSearh.equalsIgnoreCase(word3))) {
}
if (wordSearch.contains(gramer))
//it's not working because the word Artestem will contain test too, and I don't need it
You can use the matches(Regex) function with a String
String word = "test.";
boolean check = false;
if (word.matches("\w*[\.,\,]") {
check = true;
}
You can use regex for this
Matcher matcher = Pattern.compile("\\btest\\b").matcher(wordSearch);
if (matcher.find()) {
}
\\b\\b will match only a word. So "Artestem" will not match in this case.
matcher.find() will return true if there is a word test in your sentence and false otherwise.
String stringToSearch = "I trying to tasting the Artestem test. test,";
Pattern p1 = Pattern.compile("test[.,]");
Matcher m = p1.matcher(stringToSearch);
while (m.find())
{
System.out.println(m.group());
}
You can transform your String in an Array divided by words(with "split"), and search on that array , checking the last character of the words(charAt) with the character that you want to find.
String stringtoSearch = "This is a test.";
String whatIwantToFind = ",";
String[] words = stringtoSearch.split("\\s+");
for (String word : words) {
if (whatIwantToFind.equalsignorecas(word.charAt(word.length()-1);)) {
System.out.println("FIND");
}
}
What is a word? E.g.:
Is '5' a word?
Is '漢語' a word, or two words?
Is 'New York' a word, or two words?
Is 'Kraftfahrzeughaftpflichtversicherung' (meaning "automobile liability insurance") a word, or 3 words?
For some languages you can use Pattern.compile("[^\\p{Alnum}\u0301-]+") for split words. Use Pattern#split for this.
I think, you can find word by this pattern:
String notWord = "[^\\p{Alnum}\u0301-]{0,}";
Pattern.compile(notWord + "test" + notWord)`
See also: https://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html

How to split a string from the first space occurrence only Java

I tried to split a string using string.Index and string.length but I get an error that string is out of range. How can I fix that?
while (in.hasNextLine()) {
String temp = in.nextLine().replaceAll("[<>]", "");
temp.trim();
String nickname = temp.substring(temp.indexOf(' '));
String content = temp.substring(' ' + temp.length()-1);
System.out.println(content);
Use the java.lang.String split function with a limit.
String foo = "some string with spaces";
String parts[] = foo.split(" ", 2);
System.out.println(String.format("cr: %s, cdr: %s", parts[0], parts[1]));
You will get:
cr: some, cdr: string with spaces
Must be some around this:
String nickname = temp.substring(0, temp.indexOf(' '));
String content = temp.substring(temp.indexOf(' ') + 1);
string.split(" ",2)
split takes a limit input restricting the number of times the pattern is applied.
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String,%20int)
String string = "This is test string on web";
String splitData[] = string.split("\\s", 2);
Result ::
splitData[0] => This
splitData[1] => is test string
String string = "This is test string on web";
String splitData[] = string.split("\\s", 3);
Result ::
splitData[0] => This
splitData[1] => is
splitData[1] => test string on web
By default split method create n number's of arrays on the basis of given regex.
But if you want to restrict number of arrays to create after a split than pass second argument as an integer argument.

How to split String before first comma?

I have an overriding method with String which returns String in format of:
"abc,cde,def,fgh"
I want to split the string content into two parts:
String before first comma and
String after first comma
My overriding method is :
#Override
protected void onPostExecute(String addressText) {
placeTitle.setText(addressText);
}
Now how do I split the string into two parts, so that I can use them to set the text in two different TextView?
You may use the following code snippet
String str ="abc,cde,def,fgh";
String kept = str.substring( 0, str.indexOf(","));
String remainder = str.substring(str.indexOf(",")+1, str.length());
String splitted[] =s.split(",",2); // will be matched 1 times.
splitted[0] //before the first comma. `abc`
splitted[1] //the whole String after the first comma. `cde,def,fgh`
If you want only cde as the string after first comma.
Then you can use
String splitted[] =s.split(",",3); // will be matched 2 times
or without the limit
String splitted[] =s.split(",");
Don't forget to check the length to avoid ArrayIndexOutOfBound.
The below is what you are searching for:
public String[] split(",", 2)
This will give 2 string array. Split has two versions. What you can try is
String str = "abc,def,ghi,jkl";
String [] twoStringArray= str.split(",", 2); //the main line
System.out.println("String befor comma = "+twoStringArray[0]);//abc
System.out.println("String after comma = "+twoStringArray[1]);//def,ghi,jkl
String s =" abc,cde,def,fgh";
System.out.println("subString1="+ s.substring(0, s.indexOf(",")));
System.out.println("subString2="+ s.substring(s.indexOf(",") + 1, s.length()));
// Note the use of limit to prevent it from splitting into more than 2 parts
String [] parts = s.split(",", 2);
// ...setText(parts[0]);
// ...setText(parts[1]);
For more information, refer to this documentation.
Use split with regex:
String splitted[] = addressText.split(",",2);
System.out.println(splitted[0]);
System.out.println(splitted[1]);
:In this case you can use replaceAll with some regex to get this input so you can use :
System.out.println("test another :::"+test.replaceAll("(\\.*?),.*", "$1"));
If the key is just an String you can use (\\D?),.*
System.out.println("test ::::"+test.replaceAll("(\\D?),.*", "$1"));
From jse1.4String - Two split methods are new. The subSequence method has been added, as required by the CharSequence interface that String now implements. Three additional methods have been added: matches, replaceAll, and replaceFirst.
Using Java String.split(String regex, int limit) with Pattern.quote(String s)
The string "boo:and:foo", for example, yields the following results with these parameters:
Regex Limit Result
: 2 { "boo", "and:foo" }
: 5 { "boo", "and", "foo" }
: -2 { "boo", "and", "foo" }
o 5 { "b", "", ":and:f", "", "" }
o -2 { "b", "", ":and:f", "", "" }
o 0 { "b", "", ":and:f" }
String str = "abc?def,ghi?jkl,mno,pqr?stu,vwx?yz";
String quotedText = Pattern.quote( "?" );
// ? - \\? we have to escape sequence of some characters, to avoid use Pattern.quote( "?" );
String[] split = str.split(quotedText, 2); // ["abc", "def,ghi?jkl,mno,pqr?stu,vwx?yz"]
for (String string : split) {
System.out.println( string );
}
I have face the same problem in URL parameters, To resoleve it i need to split based on first ? So that the remaing String contains parameter values and they need to be split based on &.
String paramUrl = "https://www.google.co.in/search?q=encode+url&oq=encode+url";
String subURL = URLEncoder.encode( paramUrl, "UTF-8");
String myMainUrl = "http://example.com/index.html?url=" + subURL +"&name=chrome&version=56";
System.out.println("Main URL : "+ myMainUrl );
String decodeMainURL = URLDecoder.decode(myMainUrl, "UTF-8");
System.out.println("Main URL : "+ decodeMainURL );
String[] split = decodeMainURL.split(Pattern.quote( "?" ), 2);
String[] Parameters = split[1].split("&");
for (String param : Parameters) {
System.out.println( param );
}
Run Javascript on the JVM with Rhino/Nashorn « With JavaScript’s String.prototype.split function:
var str = "abc?def,ghi?jkl,mno,pqr?stu,vwx?yz";
var parts = str.split(',');
console.log( parts ); // (5) ["abc?def", "ghi?jkl", "mno", "pqr?stu", "vwx?yz"]
console.log( str.split('?') ); // (5) ["abc", "def,ghi", "jkl,mno,pqr", "stu,vwx", "yz"]
var twoparts = str.split(/,(.+)/);
console.log( parts ); // (3) ["abc?def", "ghi?jkl,mno,pqr?stu,vwx?yz", ""]
console.log( str.split(/\?(.+)/) ); // (3) ["abc", "def,ghi?jkl,mno,pqr?stu,vwx?yz", ""]
public static int[] **stringToInt**(String inp,int n)
{
**int a[]=new int[n];**
int i=0;
for(i=0;i<n;i++)
{
if(inp.indexOf(",")==-1)
{
a[i]=Integer.parseInt(inp);
break;
}
else
{
a[i]=Integer.parseInt(inp.substring(0, inp.indexOf(",")));
inp=inp.substring(inp.indexOf(",")+1,inp.length());
}
}
return a;
}
I created this function. Arguments are input string (String inp, here) and integer value(int n, here), which is the size of an array which contains values in string separated by commas. You can use other special character to extract values from string containing that character. This function will return array of integer of size n.
To use,
String inp1="444,55";
int values[]=stringToInt(inp1,2);

Java pattern to delimit string and find field

I once again need some help with this as I cannot figure out how to get a regex going.
Heres the string I want to split:
String str = "ERR||||TEST|GET|POST|UPDATE|"
I have a function which given a field index starting with 1 will return the string at that position after splitting the string. However the problem is that the regex does not return the empty strings between the delimiters as this is counted towards the field index. How can I modify this regex to include these empty fields ?
private static String extractField(String strt, int fieldNo)
{
Pattern pattern = Pattern.compile("[^|]+");
String str = strt.replaceAll("\\r", "");
Matcher matcher = pattern.matcher(str);
int i = 1;
while (matcher.find()) {
String fS = matcher.group().trim();
System.out.println("Result: \"" + fS + "\"");
if (i++==fieldNo) {
return fS;
}
}
return "";
}
Why not use split? ...
String[] x = str.split("\\|");
System.out.println(Arrays.toString(x));
As you are looking for a Pattern-based solution, you can use the regex:
(?<=(^|\|))(.*?)(?=(\||$))
Those are a positive lookahead ((?=X)) and a positive look-behind ((?<=X)). This mill match anything between two |s, or between the start of the string (^) and a |, or between a | and the end of the string ($). As lookaheads and look-behinds are zero-width assertions, they will not include the | in the groups. Also, the ? in .*? makes it non-greedy.
Code:
private static String extractField(String strt, int fieldNo)
{
Pattern pattern = Pattern.compile("(?<=(^|\\|))(.*?)(?=(\\||$))");
String str = strt.replaceAll("\\r", "");
Matcher matcher = pattern.matcher(str);
int i = 1;
while (matcher.find()) {
String fS = matcher.group().trim();
System.out.println("Result: \"" + fS + "\"");
if (i++==fieldNo) {
return fS;
}
}
return "";
}
Results for "ERR||||TEST|GET|POST|UPDATE|":
Result: "ERR"
Result: ""
Result: ""
Result: ""
Result: "TEST"
Result: "GET"
Result: "POST"
Result: "UPDATE"
Result: ""
Doing a split on | would yield what you want.
Something like this:
String s = "ERR||||TEST|GET|POST|UPDATE|";
String [] a = s.split("\\|");
for (int i=0; i<a.length; i++) {
System.out.println(a[i]);
}
You can easily upgrade your regex using look-around mechanism.
Try maybe this way [^|]+|(?<=[|]). Additional part |(?<=[|]) means "OR empty string that have | before it".
Thanks to this regex for ERR||||TEST|GET|POST|UPDATE| you will find
"ERR", "", "", "", "TEST", "GET", "POST", "UPDATE", ""
In case you don't want last "" you may use [^|]+|(?<=[|])(?=[|]). (?<=[|])(?=[|]) means "empty string that exists between two |", so result of this pattern will be
"ERR", "", "", "", "TEST", "GET", "POST", "UPDATE"

Categories

Resources