How to split the string in java by \? - java

I would like to split the special character "\".
However, it doesn't seem to work out using
a.split("\");
or
a.split("\\");

While you could escape the regular expression to String.split with the somewhat surprising
String str = "a\\b\\c";
str.split("\\\\");
it is also possible to compile a Pattern with Pattern.LITERAL and then use Pattern.split(CharSequence) like
String str = "a\\b\\c";
Pattern p = Pattern.compile("\\", Pattern.LITERAL);
String[] arr = p.split(str);
System.out.println(Arrays.toString(arr));
Which outputs
[a, b, c]

This problem is solved by using
a.split("\\\\");

Simply use \n inside the string where need. No method need to split.
"\" special character in java. It is use to skip a character. Such as String s = "I am a \"Student\" of a University!";
Hear Double cote is not allow without using "\".
We can not use "\" single in a string.
String s = "I am a \ Student of a University!";
Hear "\" will make an Err.
No method need to split using "\" Simply use "\n" Where you Need.
Or use another character with it like this
String s = "Thir is a Tiger.\'I like it very nuch!\'I it a pet!";
String s2[] = s.split("\'");
for (int i = 0; i < s2.length; i++) {
System.out.println(i+" value "+s2[i]);
}

String s = "light\\hello\\text.txt";
String s3[] = s.split(Pattern.quote("\\"));
for (int i = 0; i < s3.length; i++) {
System.out.println(i+" value "+s3[i]);
}

Related

explode function in java as in PHP

I have a variable in java, which is like this I+am+good+boy I want to get seperate them on the basis of + , in PHP I can use explode which is very handy, is there any function in java?I saw the split() function definition but that was not helpful.as it take regular expression.
Any help
Thanks
Use String.split() in regards to explode.
An example of use:
Explode :
String[] explode = "I+am+a+good+boy".split("+");
And you can reverse this like so (or "implode" it):
String implode = StringUtils.join(explode[], " ");
You have two options as I know :
String text = "I+am+good+boy";
System.out.println("Using Tokenizer : ");
StringTokenizer tokenizer = new StringTokenizer(text, "+");
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
System.out.println(" Token = " + token);
}
System.out.println("\n Using Split :");
String [] array = text.split("\\+");
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
You can try like this
String str = "I+am+a+good+boy";
String[] array = str.split("\\+");
you will get "I", "am", "a", "good", "boy" strings in the array. And you can access them as
String firstElem = array[0];
In the firstElem string you will get "I" as result.
The \\ before + because split() takes regular expressions (regex) as argument and regex has special meaning for a +. It means one or more copies of the string trailing the +.
So, if you want to get literal + sign, then you have to use escape char \\.
Just use split and escape the regex - either by hand or using the Pattern.quote() method.
String str = "I+am+a+good+boy";
String[] pieces = str.split("+")
Now you can use pieces[0], pieces[1] and so on.
More Info: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split%28java.lang.String%29

How can I remove punctuation from input text in Java?

I am trying to get a sentence using input from the user in Java, and i need to make it lowercase and remove all punctuation. Here is my code:
String[] words = instring.split("\\s+");
for (int i = 0; i < words.length; i++) {
words[i] = words[i].toLowerCase();
}
String[] wordsout = new String[50];
Arrays.fill(wordsout,"");
int e = 0;
for (int i = 0; i < words.length; i++) {
if (words[i] != "") {
wordsout[e] = words[e];
wordsout[e] = wordsout[e].replaceAll(" ", "");
e++;
}
}
return wordsout;
I cant seem to find any way to remove all non-letter characters. I have tried using regexes and iterators with no luck. Thanks for any help.
This first removes all non-letter characters, folds to lowercase, then splits the input, doing all the work in a single line:
String[] words = instring.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s+");
Spaces are initially left in the input so the split will still work.
By removing the rubbish characters before splitting, you avoid having to loop through the elements.
You can use following regular expression construct
Punctuation: One of !"#$%&'()*+,-./:;<=>?#[]^_`{|}~
inputString.replaceAll("\\p{Punct}", "");
You may try this:-
Scanner scan = new Scanner(System.in);
System.out.println("Type a sentence and press enter.");
String input = scan.nextLine();
String strippedInput = input.replaceAll("\\W", "");
System.out.println("Your string: " + strippedInput);
[^\w] matches a non-word character, so the above regular expression will match and remove all non-word characters.
If you don't want to use RegEx (which seems highly unnecessary given your problem), perhaps you should try something like this:
public String modified(final String input){
final StringBuilder builder = new StringBuilder();
for(final char c : input.toCharArray())
if(Character.isLetterOrDigit(c))
builder.append(Character.isLowerCase(c) ? c : Character.toLowerCase(c));
return builder.toString();
}
It loops through the underlying char[] in the String and only appends the char if it is a letter or digit (filtering out all symbols, which I am assuming is what you are trying to accomplish) and then appends the lower case version of the char.
I don't like to use regex, so here is another simple solution.
public String removePunctuations(String s) {
String res = "";
for (Character c : s.toCharArray()) {
if(Character.isLetterOrDigit(c))
res += c;
}
return res;
}
Note: This will include both Letters and Digits
If your goal is to REMOVE punctuation, then refer to the above. If the goal is to find words, none of the above solutions does that.
INPUT: "This. and:that. with'the-other".
OUTPUT: ["This", "and", "that", "with", "the", "other"]
but what most of these "replaceAll" solutions is actually giving you is:
OUTPUT: ["This", "andthat", "withtheother"]

Remove a specific word from a string

I'm trying to remove a specific word from a certain string using the function replace() or replaceAll() but these remove all the occurrences of this word even if it's part of another word!
Example:
String content = "is not like is, but mistakes are common";
content = content.replace("is", "");
output: "not like , but mtakes are common"
desired output: "not like , but mistakes are common"
How can I substitute only whole words from a string?
What the heck,
String regex = "\\s*\\bis\\b\\s*";
content = content.replaceAll(regex, "");
Remember you need to use replaceAll(...) to use regular expressions, not replace(...)
\\b gives you the word boundaries
\\s* sops up any white space on either side of the word being removed (if you want to remove this too).
content = content.replaceAll("\\Wis\\W|^is\\W|\\Wis$", "");
You can try replacing " is " by " ". The is with a space before and one after, replaced by a single space.
Update:
To make it work for the first "is" in the sentence, also do another replace of "is " for "". Replacing the first is and the first space, with an empty string.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String input = s.nextLine();
char c = s.next().charAt(0);
System.out.println(removeAllOccurrencesOfChar(input, c));
}
public static String removeAllOccurrencesOfChar(String input, char c) {
String r = "";
for (int i = 0; i < input.length(); i ++) {
if (input.charAt(i) != c) r += input.charAt(i);
}
return r;
}
}

how to Split String By \ in java

I am having problem to split string in java. it gives java.util.regex.Pattern.error.
String name = One\Two\Three.
String[] str = name.split("\\");
for(int i =0; i < str.length ; i++)
System.out.println(str[i]);
I put another \ as escape character but not working.
help me.
One\Two\Three is not a valid string literal (you need quotes and you need to escape the backslashes).
String name = "One\\Two\\Three.";
String[] str = name.split("\\\\");
for(int i =0; i < str.length ; i++)
System.out.println(str[i]);
works fine.
Explanation
String#split expects a regular expression. The backslash character has a special meaning inside regular expressions, so you need to escape it by using another backslash: \\ Now because the backslash character also has a special meaning inside Java string literals, you have to double each of these again, resulting in "\\\\".
You have missed the quotes
String name = "One\\Two\\Three".
You need to escape it twice:
String name = "One\\Two\\Three."
String[] str = name.split("\\\\");
for(int i =0; i < str.length ; i++)
System.out.println(str[i]);
If you want to test your pattern you should use this tool:
http://www.cis.upenn.edu/~matuszek/General/RegexTester/regex-tester.html
You cant write your test String there and your test Pattern and it can call the methods matches(), lookingAt(), find() and reset(). Also it translates your pattern to Java code (escaping the backslashes and such).

Java regex to filter phone numbers

I have following example string that needs to be filtered
0173556677 (Alice), 017545454 (Bob)
This is how phone numbers are added to a text view. I want the text to look like that
0173556677;017545454
Is there a way to change the text using regular expression. How would such an expression look like? Or do you recommend an other method?
You can do as follows:
String orig = "0173556677 (Alice), 017545454 (Bob)";
String regex = " \\(.+?\\)";
String res = orig.replaceAll(regex, "").replaceAll(",", ";");
// ^remove all content in parenthesis
// ^ replace comma with semicolon
Use the expression in android.util.Patterns
Access the static variable
Patterns.PHONE
or use this expression here (Android Source Code)
Here's a resource that can guide you :
http://www.zparacha.com/validate-email-ssn-phone-number-using-java-regular-expression/
This solution works with phone numbers separated with any string that does not contain numbers:
String orig = "0173556677 (Alice), 017545454 (Bob)";
String[] numbers = orig.split("\\D+"); //split at everything that is not a digit
StringBuilder sb = new StringBuilder();
if (numbers.length > 0) {
sb.append(numbers[0]);
for (int i = 1; i < numbers.length; i++) { //concatenate all that is left
sb.append(";");
sb.append(numbers[i]);
}
}
String res = sb.toString();
or, with com.google.common.base.Joiner:
String[] numbers = orig.split("\\D+"); //split at everything that is not a digit
String res = Joiner.on(";").join(numbers);
PS. There is a minor deviation from the requirements in the best voted example, but it seems I cannot just add one character (should be replaceAll(", ", ";"), with a space after the coma, or a \\s) and I do not want to mess somebody's code.

Categories