I have a string in java which contains text as
Hello user your choice is in (1,2,3,4) as selected by you.
Now I want to remove choice is in (1,2,3,4) from this string with "".
I cannot directly do it using replace() in java as data inside the () is dynamic and changes every time.
Output required
Hello user your as selected by you.
I tried using regex but it failed and did not work, my regex
(?s)(\\choice is in .*?\\\\(\\\\)
You may use
.replaceAll("\\s+choice\\s+is\\s+in\\s+\\([^()]*\\)", "")
See the regex demo.
\s+ - 1+ whitespaces
choice\s+is\s+in - choice is in with any 1+ whitespaces in between words
\s+ - 1+ whitespaces
\([^()]*\) - a (, then any 0+ chars other than ( and ) and then a )
See Java demo:
String s = "Hello user your choice is in (1,2,3,4) as selected by you.";
System.out.println(s.replaceAll("\\s+choice\\s+is\\s+in\\s+\\([^()]*\\)", ""));
// => Hello user your as selected by you.
Given below is a non-regex solution:
public class Main {
public static void main(String[] args) {
String s = "Hello user your choice is in (1,2,3,4) as selected by you.";
int start = s.indexOf(" choice is in (");
int end = s.indexOf(")", start);// Index of `)` after the index, `start`
s = s.substring(0, start) + s.substring(end + 1);
System.out.println(s);
}
}
Output:
Hello user your as selected by you.
Please refer below code.
String pattern = "choice is in (.*?) ";
String userString = "Hello user your choice is in (1,2,3,4) as selected by you";
userString = userString.replaceAll(pattern, "");
System.out.println(userString);
Output will be :
Hello user your as selected by you
Try This:
String pattern = "choice is in (.*) as";
String userString = "Hello user your choice is in (1,2,3,4) as selected by you";
userString = userString.replaceAll(pattern, "as");
System.out.println(userString);
And the output would be:
Hello user your as selected by you
Related
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
I usually don't ask for help but here I really need it.
I have the following code example:
String text = "aa aab aa aab";
text = text.replace("aa", "--");
System.out.println(text);
Console output: -- --b -- --b
I have a question, how do I only replace aa parts of the string not aab included.
So the console output is:
-- aab -- aab
I have another example:
String text = "111111111 1";
text = text.replace("1", "-");
System.out.println(text);
Console output: --------- -
I only want to replace a single character, not all the same ones who are placed together.
So the console output is:
111111111 -
Are there any Java shortcuts for situations like these? I can't figure it out, how to only replace specific part of the string. Any help would be appreciated :)
You could use a regular expression with String.replaceAll(String, String). By using word boundaries (\b), something like
String[] texts = { "aa aab aa aab", "111111111 1" };
String[] toReplace = { "aa", "1" };
String[] toReplaceWith = { "--", "-" };
for (int i = 0; i < texts.length; i++) {
String text = texts[i];
text = text.replaceAll("\\b" + toReplace[i] + "\\b", toReplaceWith[i]);
System.out.println(text);
}
Outputs (as requested)
-- aab -- aab
111111111 -
You can use a regex
String text = "111111111 1";
text = text.replaceAll("1(?=[^1]*$)", "");
System.out.println(text);
Explanation:
String.replaceAll takes a regex contrarily to String.replace which takes a litteral to replace
(?=reg) the right part of the regex must be followed by a string matching the regex reg, but only the right part will be captured
[^1]* means a sequence from 0 to any number of characters different from '1'
$ means the end of the string is reached
In plain english, this means: Please replace by an empty string all the occurrences of the '1' character followed by any number of characters different from '1' until the end of the string.
We can use the StringTokenizer present in Java to acheive the solution for any kind of input. Below is the sample solution,
public class StringTokenizerExample {
/**
* #param args
*/
public static void main(String[] args) {
String input = "aa aab aa aab";
String output = "";
String replaceWord = "aa";
String replaceWith = "--";
StringTokenizer st = new StringTokenizer(input," ");
System.out.println("Before Replace: "+input);
while (st.hasMoreElements()) {
String word = st.nextElement().toString();
if(word.equals(replaceWord)){
word = replaceWith;
if(st.hasMoreElements()){
word = " "+word+" ";
}else{
word = " "+word;
}
}
output = output+word;
}
System.out.println("After Replace: "+output);
}
I want to surround all tokens in a text with tags in the following manner:
Input: " abc fg asd "
Output:" <token>abc</token> <token>fg</token> <token>asd</token> "
This is the code I tried so far:
String regex = "(\\s)([a-zA-Z]+)(\\s)";
String text = " abc fg asd ";
text = text.replaceAll(regex, "$1<token>$2</token>$3");
System.out.println(text);
Output:" <token>abc</token> fg <token>asd</token> "
Note: for simplicity we can assume that the input starts and ends with whitespaces
Use lookaround:
String regex = "(?<=\\s)([a-zA-Z]+)(?=\\s)";
...
text = text.replaceAll(regex, "<token>$1</token>");
If your tokens are only defined with a character class you don't need to describe what characters are around. So this should suffice since the regex engine walks from left to right and since the quantifier is greedy:
String regex = "[a-zA-Z]+";
text = text.replaceAll(regex, "<token>$0</token>");
// meaning not a space, 1+ times
String result = input.replaceAll("([^\\s]+)", "<token>$1</token>");
this matches everything that isn't a space. Prolly the best fit for what you need. Also it's greedy meaning it will never leave out a character that it shouldn't ( it will never find the string "as" in the string "asd" when there is another character with which it matches)
I have below String
string = "Book Your Domain And Get\n \n\n \n \n \n Online Today."
string = str.replace("\\s","").trim();
which returning
str = "Book Your Domain And Get Online Today."
But what is want is
str = "Book Your Domain And Get Online Today."
I have tried Many Regular Expression and also googled but got no luck. and did't find related question, Please Help, Many Thanks in Advance
Use \\s+ instead of \\s as there are two or more consecutive whitespaces in your input.
string = str.replaceAll("\\s+"," ")
You can use replaceAll which takes a regex as parameter. And it seems like you want to replace multiple spaces with a single space. You can do it like this:
string = str.replaceAll("\\s{2,}"," ");
It will replace 2 or more consecutive whitespaces with a single whitespace.
First get rid of multiple spaces:
String after = before.trim().replaceAll(" +", " ");
If you want to just remove the white space between 2 words or characters and not at the end of string
then here is the
regex that i have used,
String s = " N OR 15 2 ";
Pattern pattern = Pattern.compile("[a-zA-Z0-9]\\s+[a-zA-Z0-9]", Pattern.CASE_INSENSITIVE);
Matcher m = pattern.matcher(s);
while(m.find()){
String replacestr = "";
int i = m.start();
while(i<m.end()){
replacestr = replacestr + s.charAt(i);
i++;
}
m = pattern.matcher(s);
}
System.out.println(s);
it will only remove the space between characters or words not spaces at the ends
and the output is
NOR152
Eg. to remove space between words in a string:
String example = "Interactive Resource";
System.out.println("Without space string: "+ example.replaceAll("\\s",""));
Output:
Without space string: InteractiveResource
If you want to print a String without space, just add the argument sep='' to the print function, since this argument's default value is " ".
//user this for removing all the whitespaces from a given string for example a =" 1 2 3 4"
//output: 1234
a.replaceAll("\\s", "")
String s2=" 1 2 3 4 5 ";
String after=s2.replace(" ", "");
this work for me
String string_a = "AAAA BBB";
String actualTooltip_3 = string_a.replaceAll("\\s{2,}"," ");
System.out.println(String actualTooltip_3);
OUTPUT will be:AAA BBB
I want to perform the following functionality :
From a given paragraph extract the given String, like
String str= "Hello this is paragraph , Ali#yahoo.com . i am entering random email here as this one AHmar#gmail.com " ;
What I have to do is to parse the whole paragraph, read the Email address, and print their server names , i have tried it using for loop with substring method , did use indexOf , but might be my logic is not that good to get it , can someone help me with it please?
You need to use Regular Expression for this case.
Try the below Regex: -
String str= "Hello this is paragraph , Ali#yahoo.com . i am " +
"entering random email here as this one AHmar#gmail.com " ;
Pattern pattern = Pattern.compile("#(\\S+)\\.\\w+");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
OUTPUT: -
yahoo
gmail
UPDATE: -
Here's the code with substring and indexOf: -
String str= "Hello this is paragraph , Ali#yahoo.com . i am " +
"entering random email here as this one AHmar#gmail.com " ;
while (str.contains("#") && str.contains(".")) {
int index1 = str.lastIndexOf("#"); // Get last index of `#`
int index2 = str.indexOf(".", index1); // Get index of first `.` after #
// Substring from index of # to index of .
String serverName = str.substring(index1 + 1, index2);
System.out.println(serverName);
// Replace string by removing till the last #,
// so as not to consider it next time
str = str.substring(0, index1);
}
You need to use a regular expression to extract the email. Start off with this test harness code. Next, construct your regular expression and you should be able to extract the email address.
Try this:-
String e= "Hello this is paragraph , Ali#yahoo.com . i am entering random email here as this one AHmar#gmail.comm";
e= e.trim();
String[] parts = e.split("\\s+");
for (String e: parts)
{
if(e.indexOf('#') != -1)
{
String temp = e.substring(e.indexOf("#") + 1);
String serverName = temp.substring(0, temp.indexOf("."));
System.out.println(serverName); }}