Replacing a special character (along with space is considered same) - java

Have a look at this string String str = "first,second, there"; . there are , and , ( there's a space after the second comma). How do I express it in RegEx as .replaceAll()'s parameters so the
output would be :
"first second there". <-- the amount on each space will be same.
I had tried some combinations but still fail. One of them is :
String temp2 = str.replaceAll("[\\,\\, ]", " "); will print first second there.
Thanks before.

Simply use , * to match comma followed by zero or more spaces and replace with single space.
String str = "first,second, there";
System.out.println(str.replaceAll(", *", " "));
output:
first second there
Read more about Java Pattern
Greedy quantifiers
X? X, once or not at all
X* X, zero or more times
X+ X, one or more times

String temp2 = str.replaceAll(", ?", " ");
The ? Means optional (ie zero or once), or
String temp2 = str.replaceAll(", *", " ");
Where the * means zero or more (many) spaces

Related

How to remove space after the decimal point without removing other spaces?

I have one String that has multiple values in single string. I just want to remove the space after decimal point only without removing other spaces from string.
String testString = "EB:3668. 19KWh DB:22. 29KWh";
testString = testString.trim();
String beforeDecimal = testString.substring(0, testString.indexOf("."));
String afterDecimal = testString.substring(testString.indexOf("."));
afterDecimal = afterDecimal.replaceAll("\\s+", "");
testString = beforeDecimal + afterDecimal;
textView.setText(testString);
Here as in my string there is two values in single string
EB:3668. 19KWh and DB:22. 29KWh.
I just want to remove space after decimal point and make String like this:
EB:3668.19KWh DB:22.29KWh
You can use 2 capture groups and match the space in between. In the replacement use the 2 groups without the space.
(\d+\.)\h+(\d+)
Regex demo
String testString="EB:3668. 19KWh DB:22. 29KWh";
String afterDecimal = testString.replaceAll("(\\d+\\.)\\h+(\\d+)","$1$2");
System.out.println(afterDecimal);
Output
EB:3668.19KWh DB:22.29KWh
Or a bit more specific pattern could be including the KWh:
\b(\d+\.)\h+(\d+KWh)
Regex demo
Just use string.replaceAll("\\. ", ".");
Thanks to Henry for pointing out I had to escape the .
I'm not in front of an editor right now, but wouldn't you be able to do this with the replaceAll method in a single line, without breaking it up?
var text = testString.replaceAll(". ", ".");
You can remove unnecessary spaces between the decimal point and the fractional part as follows. This code also removes other extra spaces:
String testString = " EB:3668. 19KWh DB:22. 29KWh ";
String test2 = testString
// remove leading and trailing spaces
.trim()
// replace non-empty sequences of space
// characters with a single space
.replaceAll("\\s+", " ")
// remove spaces between the decimal
// point and the fractional part
// regex groups:
// (\\d\\.) - $1 - digit and point
// ( ) - $2 - space
// (\\d) - $3 - digit
.replaceAll("(\\d\\.)( )(\\d)", "$1$3");
System.out.println(test2); //EB:3668.19KWh DB:22.29KWh
See also: How do I remove all whitespaces from a string?

trying to find a word with seperators in string

i have a full string like this - "Hello all you guys"
and i have a bad word like "all"
now i managed to find the second string in the first that's easy,
but let's say my first string is "Hello a.l.l you guys"
or "Hello a,l,l you guys"
or even "Hello a l l you guys"
is there a regex way to find it ?
what i've got so far is
String wordtocheck =pair.getKey().toString();
String newerstr = "";
for(int i=0;i<wordtocheck.length();i++)
newerstr+=wordtocheck.charAt(i)+"\\.";
Pattern.compile("(?i)\\b(newerstr)(?=\\W)").matcher(currentText.toString());
but it doesn't do the trick
thanks to all helpers
You may build the pattern dynamically by inserting \W* (=zero or more non-word chars, that is, chars that are not letters, digits or underscore) in between the characters of a keyword to search for:
String s = "Hello a l l you guys";
String key = "all";
String pat = "(?i)\\b" + TextUtils.join("\\W*", key.split("")) + "\\b";
System.out.println("Pattern: " + pat);
Matcher m = Pattern.compile(pat).matcher(s);
if (m.find())
{
System.out.println("Found: " + m.group());
}
See the online demo (String.join is used instead of TextUtils.join since this is a Java demo)
If there can be non-word chars in the search words, you need to replace \b word boundaries with (?<!\\S) (the initial \b) and (?!\\S) (instead of the trailing \b), or remove altogether.
Try this
String str="Hello .a-l l? guys";
str=str.replaceAll("\\W",""); //replaces all non-words chars with empty string.
str is now "Helloallguys"

How to get the index of the first space occurring before a particular character

I have a file which has line in the format
xbox one gaming-consoles:xbox-one-games:gaming-controllers
xbox one games xbox-one-games
xbox 360 games xbox-360-games:gaming-consoles
xbox 360 gaming-consoles:xbox-360-games:gaming-controllers
Now i want to split the lines in two parts . The logic of splitting is that it should be done at the first space before the character ':'
so the splited text should look like
xbox one gaming-consoles:xbox-one-games:gaming-controllers
xbox one games ox-one-games:gaming-controllers
xbox 360 games xbox-360-games:gaming-consoles
and so on....
How can this be acheived ?
You could use lastIndexOfto get the position within the string of the last space, then use substring to split the string into two different variables.
String s1 = "test string with lots of spaces";
String s2 = s1.substring(0, s1.lastIndexOf(" "); //From the first character until the last space
String s3 = s1.substring(s1.lastIndexOf(" ")+1); //Index of last space+1 to end.
System.out.println(s1 + "\n" + s2 + "\n" + s3);
Which gives the output of:
test string with lots of spaces
test string with lots of
spaces
A small problem would be that the string containing the first half would still contain the whitespace at the end of the string, but could be easily mediated if needed with trim.
Regarding
The logic of splitting is that it should be done at the first space before the character :
Use a positive lookahead based regex:
String s = "xbox one gaming-consoles:xbox-one-games:gaming-controllers and more here";
String[] chunks = s.split(" ++(?=[^ :]*:)", 2);
System.out.println(Arrays.toString(chunks));
// => [xbox one, gaming-consoles:xbox-one-games:gaming-controllers and more here]
See the Java demo
The split will yield one (if no match is found) or 2 chunks (since the limit argument is passed, 2). The split will happen at 1 or more spaces (see " ++") that are followed with 0+ chars other than a space and : (see [^ :]*) followed with a :.
Maybe you can use a regex to extract the second part of each line.
(\\s[\\S]+)(?=:).+ will lookahead (\\s[\\S]+) to check if it followed by a :. (\\s[\\S]+) select the group that begins with a space \s and followed by nonspace characters [\S]+.
Here is the sample code:
import java.util.regex.*;
public class TestRegex {
public static void main(String []args){
String[] line = new String[] {
"xbox one gaming-consoles:xbox-one-games:gaming-controllers",
"xbox one games xbox-one-games",
"xbox 360 games xbox-360-games:gaming-consoles",
"xbox 360 gaming-consoles:xbox-360-games:gaming-controllers "
};
String regex = "(\\s[\\S]+)(?=:).+";
Pattern re = Pattern.compile(regex);
for (String ln : line) {
Matcher m = re.matcher(ln);
if (m.find()) {
System.out.println(m.group(0));
}
}
}
}

replace number to words in right position in java

Actually I'm trying to replace number to words in the sentence that giving by user. This case date format; For example: My birthday is on 16/6/2000 and I'm newbie to the java --> become ---> My birthday is on sixteenth july two thousand and I'm newbie to the java
Here is code:
Scanner reader = new Scanner(System.in);
System.out.println("Enter any numbers: ");
String nom = reader.nextLine(); // get input from user
//checking contains that has "/" or not
if(nom.contains("/")){
String parts[] = nom.split("[/]");
String part1 = parts[0]; //data before "/" will be stored in the first array
String day[] = part1.split("\\s+");// split between space
String get_day = day[day.length -1];// get last array
String get_month = parts[1]; //data in the between of "/" will be stored in the second array
String part3 = parts[2]; // data after "/" will be stored in the third array
String year[] = part3.split("\\s+");// split between space
String get_year = year[0];// get first array
String s = NumberConvert.convert(Integer.parseInt(get_day)) +
NumberConvert.convert(Integer.parseInt(get_month)) +
NumberConvert.convert(Integer.parseInt(get_year));
String con = nom.replaceAll("[0-9].*/[0-9].*/[0-].*", s); // replace number to word
System.out.println(con); // print the data already converted
} else {....}
But the result that I have got is:
My birthday is on sixteenth july two thousand
//"and I'm newbie to the java" is disappear [How to solve it]//
How to solve it. Actually I want to get value before and after of "/" slash and convert it to words and replace it as a original input from user.
What I have tried is:
String con = nom.replaceAll("[0-9].*/[0-9].*/[0-9999]", s); // a bit change [0-9].* to [0-9999]
But output become like this:
My birthday is on sixteenth july two thousand 000 and I'm newbie to the java
//after two thousand index "000" is appearing
The regex is wrong:
[0-9].*/[0-9].*/[0-].*
What it means:
[0-9] match a single number in the range between 0 and 9
.* matches any character (except newline) between zero and unlimited times, as many times as possible, giving back as needed [greedy]
/ matches the character / literally
[0-9] match a single number in the range between 0 and 9
.* matches any character (except newline) between zero and unlimited times, as many times as possible, giving back as needed [greedy]
/ matches the character / literally
[0-] match a single number in the list 0- literally
.* matches any character (except newline) between zero and unlimited times, as many times as possible, giving back as needed [greedy]
It should be:
[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]
Or, better:
\d{2}/\d{2}/\d{4}
You can also use below regex pattern to get all the numbers from String:
String st = "My birthday is on 16/6/2000 and I'm newbie to the java, using since 2015";
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher(st);
while (m.find()) {
System.out.println(m.group());
}

String.replaceAll Strange Behaviour

String s = "hi hello";
s = s.replaceAll("\\s*", " ");
System.out.println(s);
I have the code above, but I can't work out why it produces
h i h e l l o
rather than
hi hello
Many thanks
Use + quantifier to match 1 or more spaces instead of *: -
s = s.replaceAll("\\s+", " ");
\\s* means match 0 or more spaces, and will match an empty character before every character and is replaced by a space.
The * matches 0 or more spaces, I think you want to change it to + to match 1 or more spaces.

Categories

Resources