How can i put a string in one line - java

i'm doing some conversion, from Hex to Ascii, when i convert the string, i got the following example:
F23C040100C1
100D200000000000
0000
I know that the string is coming like this, because of the base 16, but i want too put it in just one line, like this:
F23C040100C1100D2000000000000000
How can i do that?
I have tried:
mensagem.replaceAll("\r\n", " ");

There are multiple problems you could be running into, so I'll cover all them in this answer.
First, any methods on String which appear to modify it actually return a new instance of String. That means if you do this:
String something = "Hello";
something.replaceAll("l", "");
System.out.println(something); //"Hello"
You'll want to do
something = something.replaceAll("l", "");
Or in your case
mensagem = mensagem.replaceAll("\r\n", " ");
Secondly, there might not be any \r in the newline, but there is a \n, or vice versa. Because of that, you want to say that
if \r exists, remove it. if \n exists, also remove it
You can do so like this:
mensagem = mensagem.replaceAll("\r*\n*", " ");
The * operator in a regular expression says to match zero or more of the preceding symbol.

mensagem.replaceAll("\r\n|\r|\n", "");

Related

Java - Remove only the first backslash

Small Java question regarding how to remove only the first backslash please.
I have a string which looks like this:
String s = "\\u6df1\\u5733";
Please note, there are two backslashes, and multiple occurrences.
Hence, when this is displayed, the visual result is:
\深\圳
I would like to just remove any extra backslashes, having a result like this:
深圳
So far, I have tried this:
String s = "\\u6df1\\u5733";
String ss = s.replaceAll("\\", "");
But it is still not working.
What is the correct solution please in order to get 深圳 from "\\u6df1\\u5733" please?
Thank you
Try this.
String s = "\\u6df1\\u5733";
Pattern UNICODE_ESCAPE = Pattern.compile("\\\\u[0-9a-f]+", Pattern.CASE_INSENSITIVE);
String ss = UNICODE_ESCAPE.matcher(s).results()
.map(x -> new String(Character.toChars(Integer.parseInt(x.group().substring(2), 16))))
.collect(Collectors.joining());
System.out.println(ss);
UNICODE_ESCAPE.matcher(s).results() returns the stream of MatcherResult.
x.group().substring(2) extracts hexadecimal part "xxxx" from "\\uxxxx".
Integer.parseInt(..., 16) converts it to an integer value that is a code point.
Caracter.toChars() converts it to an array of char.
new String(...) converts it to an String. And .collect(Collectors.joining()) concatenates the all of them.
output:
深圳
Going by this output:
\深\圳
you actually have two unicode characters each preceded by one backslash.
In a Java string literal, that would look like this:
String s = "\\\u6df1\\\u5733";
If you want to remove the backslashes (\\) and leave the unicode character codes (e.g. \u6df1), then you just need replace.
String ss = s.replace("\\", "");
replaceAll won't work for this, because it requires a regular expression as its first argument.

Regular expression for string with apostrophes

I'm trying to build regex which will filter form string all non-alphabetical characters, and if any string contains single quotes then I want to keep it as an exception to the rule.
So for example when I enter
car's34
as a result I want to get
car's
when I enter
*&* Lisa's car 0)*
I want to get
Lisa's
at the moment I use this:
string.replaceAll("[^A-Za-z]", "")
however, it gives me only alphabets, and removed the desired single quotas.
This will also remove apostrophes that are not "part if words":
string = string.replaceAll("[^A-Za-z' ]+|(?<=^|\\W)'|'(?=\\W|$)", "")
.replaceAll(" +", " ").trim();
This first simply adds an apostrophe to the list of chars you want to keep, but uses look arounds to find apostrophes not within words, so
I'm a ' 123 & 'test'
would become
I'm a test
Note how the solitary apostrophe was removed, as well as the apostrophes wrapping test, but I'm was preserved.
The subsequent replaceAll() is to replace multiple spaces with a single space, which will result if there's a solitary apostrophe in the input. A further call to trim() was added in case it occurs at the end of the input.
Here's a test:
String string = "I'm a ' 123 & 'test'";
string = string.replaceAll("[^A-Za-z' ]+|(?<=^|\\W)'|'(?=\\W|$)", "").replaceAll(" +", " ").trim();
System.out.println(string);
Output:
I'm a test
Isn't this working ?
[^A-Za-z']
The obvious solution would be:
string.replaceAll("[^A-Za-z']", "")
I suspect you want something more.
You can try the regular expression:
[^\p{L}' ]
\p{L} denote the category of Unicode letters.
In ahother hand, you need to use a constant of Pattern for avoid recompiled the expression every time, something like that:
private static final Pattern REGEX_PATTERN =
Pattern.compile("[^\\p{L}' ]");
public static void main(String[] args) {
String input = "*&* Lisa's car 0)*";
System.out.println(
REGEX_PATTERN.matcher(input).replaceAll("")
); // prints " Lisa's car "
}
#Bohemian has a good idea but word boundaries are called for instead of lookaround:
string.replaceAll("([^A-Za-z']|\B'|'\B)+", " ");

removing white spaces from string value

i have a link http://localhost:8080/reporting/pvsUsageAction.do?form_action=inline_audit_view&days=7&projectStatus=scheduled&justificationId=5&justificationName= No Technicians in Area in my struts based web application.
The variable in URL justificationName have some spaces before its vales as shown. when i get value of justificationName using request.getParameter("justificationName") it gives me that value with spaces as given in the URL. i want to remove those spaces. i tried trim() i tries str = str.replace(" ", ""); but any of them did not removed those spaces. can any one tell some other way to remove the space.
Noted one more thing that i did right click on the link and opened the link into new tab there i noticed that link looks like.
http://localhost:8080/reporting/pvsUsageAction.do?form_action=inline_audit_view&days=7&projectStatus=scheduled&justificationId=5&justificationName=%A0%A0%A0%A0%A0%A0%A0%A0No%20Technicians%20in%20Area
Notable point is that in the address bar it shows %A0 for white spaces and also show %20 for space as well see the link and tell the difference please if any one have idea about it.
EDIT
Here is my code
String justificationCode = "";
if (request.getParameter("justificationName") != null) {
justificationCode = request.getParameter("justificationName");
}
justificationCode = justificationCode.replace(" ", "");
Note: replace function remove the space from inside the string but not removing starting spaces.
e-g if my string is " This is string" after using replace it becomes " Thisisstring"
Thanks in advance
Strings are immutable in Java, so the method doesn't change the string you pass but returns a new one. You must use the returned value :
str = str.replace(" ", "");
Manual trim
You need to remove the spaces the string. This will remove any number of consecutive spaces.
String trimmed = str.replaceAll(" +", "");
If you want to replace all whitespace characters:
String trimmed = str.replaceAll("\\s+", "");
URL Encoding
You could also use an URLEncoder, which sounds like a more appropriate way to go:
import java.net.UrlEncoder;
String url = "http://localhost:8080/reporting/" + URLEncoder.encode("pvsUsageAction.do?form_action=inline_audit_view&days=7&projectStatus=scheduled&justificationId=5&justificationName= No Technicians in Area", "ISO-8859-1");
You have to assign the result of the replace(String regex, String replacement) operation to another variable. See the Javadoc for the replace(String regex, String replacement) method. It returns a brand new String object and this is because the String(s) in Java are immutable. In your case, you can simply do the following
String noSpacesString = str.replace("\\s+", "");
You can use replaceAll("\\s","") It will remove all white space.
If you are trying to remove the trailing and ending white spaces, then
s = s.trim();
Or if you want to remove all the spaces the use :
s = s.replace(" ","");
There are two ways of doing one is regular expression based or your own way of implementing the logic
replaceAll("\\s","")
or
if (text.contains(" ") || text.contains("\t") || text.contains("\r")
|| text.contains("\n"))
{
//code goes here
}

String manipulation in java using replaceAll()

I have string of the following form:
भन्‍‌ने [-0.4531954191090929, 0.7931147934270654, -0.3875088408737827, -0.09427394940704822, 0.10065554475134718, -0.22044284832864797, 0.3532556916833505, -1.8256229909222224, 0.8036832111904731, 0.3395868096795993]
Whereever [ or ] or , char are present , I just want to remove them and i want each of the word and float separated by a space. It is follows:
भन्‍‌ने -0.4531954191090929 0.7931147934270654 -0.3875088408737827 -0.09427394940704822 0.10065554475134718 -0.22044284832864797 0.3532556916833505 -1.8256229909222224 0.8036832111904731 0.3395868096795993
I am representing each of these string as line. i did following:
line.replaceAll("([|]|,)$", " ");
But it didn't work for me. There was nothing change in the input line. Any help is really appreciated.
Strings are immutable. Try
line = line.replaceAll("([|]|,)$", " ");
Or to be a bit more verbose, but avoiding regular expressions:
char subst = ' ';
line = line.replace('[', subst).replace(']', subst).replace(',', subst);
In Java, strings are immutable, meaning that the contents of a string never change. So, calling
line.replaceAll("([|]|,)$", " ");
won't change the contents of line, but will return a new string. You need to assign the result of the method call to a variable. For instance, if you don't care about the original line, you can write
line = line.replaceAll("([|]|,)$", " ");
to get the effect you originally expected.
[ and ] are special characters in a regular expression. replaceAll is expected a regular expression as its first input, so you have to escape them.
String result = line.replaceAll("[\\[\\],]", " ");
Cannot tell what you were trying to do with your original regex, why you had the $ there etc, would need to understand what you were expecting the things you put there to do.
Try
line = "asdf [foo, bar, baz]".replaceAll("(\\[|\\]|,)", "");
The regex syntax uses [] to define groups like [a-z] so you have to mask them.

Replacing strings in java question

Say I have a java source file saved into a String variable like so.
String contents = Utils.getTextFromFile(new File(fileName));
And say there is a line of text in the source file like so
String x = "Hello World\n";
Notice the newline character at the end.
In my code, I know of the existence of Hello World, but not Hello World\n
so therefore a call to
String search = "Hello World";
contents = contents.replaceAll(search, "Something Else");
will fail because of that newline character. How can I make it so it will match in the case of one or many newline characters? Could this be a regular expression I add to the end search variable?
EDIT:
I am replacing string literals with variables. I know the literals, but I dont know if they have a newline character or not. Here is an example of the code before my replacement. For the replacment, I know that application running at a time. exists, but not application running at a time.\n\n
int option = JOptionPane.showConfirmDialog(null,"There is another application running. There can only be one application\n" +
"application running at a time.\n\n" +
"Press OK to close the other application\n" +
"Press Cancel to close this application",
"Multiple Instances of weh detected",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.ERROR_MESSAGE);
And here is an example after my replacement
int option = JOptionPane.showConfirmDialog(null,"There is another application running. There can only be one application\n" +
"application running at a time.\n\n" +
"Press OK to close the other application\n" +
"PRESS_CANCEL_TO_CLOSE",
"MULTIPLE_INSTANCES_OF",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.ERROR_MESSAGE);
Notice that all of the literals without newlines get replaced, such as "Multiple Instances of weh Detected" is now "MULTIPLE_INSTANCES_OF" but all of the ones with new lines do not. I am thinking that there is some regular expression I can add on to handle one or many newline characters when it tries to the replace all.
well since its actually a regular expression that is passed as the first argument you could try something like this as the first argument
String search = "[^]?[H|h]ello [W|w]orld[\n|$]?"
which will search for hello world everywhere in the start and the end of a line wether it has a \n or not.
a bit redundant and as stated it should not matter but... apparantly it does
try it (made it nifty so it matches capital as well as regular letters :P... just overdoin it)
If you're only replacing string literals, and you're ok with replacing every occurrence of the literal (not just the first one) then you should use the replace method instead of replaceAll.
Your first example should change to this:
String search = "Hello World";
contents = contents.replace(search, "Something Else");
The replaceAll does a regular expression replacement instead of a string literal replacement. This is generally slower, and is not strictly necessary for your use case.
Note that this answer assumes that the trailing newline characters can be left in the string (which you've said you are ok with in the comments).
String search = "Hello World\n\n\n";
search.replaceAll ("Hello World(\\n*)", "Guten Morgen\1");
\1 captures the first group, marked by (...), counting from the opening parenthesis. \n+ is \n for newline, but the backslash needs to be masked in Java, leading to two backslashes. * means 0 to n, so it would catch 0, 1, 2, ... newlines.
As the commenters noted, the \n should not mess this up. However, if you are ok with removing the new lines, you can try this:
contents = contents.replaceAll("search"+"\\n*", "Something Else");
As per your question you need to pass following charator
public String replaceAll(String regex, String replacement)
The two parameters are –
regex – the regular expression to match
replacement – the string to be substituted for every match
Some other method is: -
replace(char oldChar, char newChar)
replace(CharSequence target, CharSequence replacement)
replaceFirst(String regex, String replacement)
example is
import java.lang.String;
public class StringReplaceAllExample {
public static void main(String[] args) {
String str = "Introduction 1231 to 124 basic 1243 programming 34563 concepts 5455";
String Str1 = str.replaceAll("[0-9]+", "");
System.out.println(Str1);
Str1 = str.replaceAll("[a-zA-Z]+", "Java");
System.out.println(Str1);
}
}

Categories