How can I replace specified whitespaces in string?












1















I have a string:



2+3-{Some value}


How can I prevent user from adding spaces between operators and operands, but allow to add spaces between curly braces? Maybe regex?



Update



I'm working on real time validating formula. All validations including whitespace removal are done using TextWatcher. My simplified code looks like this:



private val formulaWatcher: TextWatcher = object : TextWatcher {
override fun afterTextChanged(s: Editable?) = Unit

override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit

override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
//Delay used here to avoid IndexOfBoundExceptions which arise because of a setSelection() method, it works with a little delay
Handler().postDelayed({
removeSpaces(s)
}, 100)
}
}


Remove spaces function:



private fun removeSpaces(s: CharSequence) {
if (s.last().isWhitespace()) {
val textWithoutSpaces = s.replace(Regex("\s"), "")
getText().clear()
append(textWithoutSpaces)
setSelection(textWithoutSpaces.length)
}
}









share|improve this question




















  • 1





    Please read "How to create a Minimal, Complete, and Verifiable example". Then use the edit link to improve your question (do not add more information via comments). Otherwise we are not able to answer your question and help you. Show us a complete example, and the code you have, and tell us where it deviates from your expectations.

    – GhostCat
    Nov 13 '18 at 8:55













  • Maybe regex? - gooed idea using String::replaceAll

    – Scary Wombat
    Nov 13 '18 at 8:59











  • @ScaryWombat replaceAll will replace all whitespaces in string. I need to save spaces between curly braces

    – Skullper
    Nov 13 '18 at 9:07
















1















I have a string:



2+3-{Some value}


How can I prevent user from adding spaces between operators and operands, but allow to add spaces between curly braces? Maybe regex?



Update



I'm working on real time validating formula. All validations including whitespace removal are done using TextWatcher. My simplified code looks like this:



private val formulaWatcher: TextWatcher = object : TextWatcher {
override fun afterTextChanged(s: Editable?) = Unit

override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit

override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
//Delay used here to avoid IndexOfBoundExceptions which arise because of a setSelection() method, it works with a little delay
Handler().postDelayed({
removeSpaces(s)
}, 100)
}
}


Remove spaces function:



private fun removeSpaces(s: CharSequence) {
if (s.last().isWhitespace()) {
val textWithoutSpaces = s.replace(Regex("\s"), "")
getText().clear()
append(textWithoutSpaces)
setSelection(textWithoutSpaces.length)
}
}









share|improve this question




















  • 1





    Please read "How to create a Minimal, Complete, and Verifiable example". Then use the edit link to improve your question (do not add more information via comments). Otherwise we are not able to answer your question and help you. Show us a complete example, and the code you have, and tell us where it deviates from your expectations.

    – GhostCat
    Nov 13 '18 at 8:55













  • Maybe regex? - gooed idea using String::replaceAll

    – Scary Wombat
    Nov 13 '18 at 8:59











  • @ScaryWombat replaceAll will replace all whitespaces in string. I need to save spaces between curly braces

    – Skullper
    Nov 13 '18 at 9:07














1












1








1








I have a string:



2+3-{Some value}


How can I prevent user from adding spaces between operators and operands, but allow to add spaces between curly braces? Maybe regex?



Update



I'm working on real time validating formula. All validations including whitespace removal are done using TextWatcher. My simplified code looks like this:



private val formulaWatcher: TextWatcher = object : TextWatcher {
override fun afterTextChanged(s: Editable?) = Unit

override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit

override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
//Delay used here to avoid IndexOfBoundExceptions which arise because of a setSelection() method, it works with a little delay
Handler().postDelayed({
removeSpaces(s)
}, 100)
}
}


Remove spaces function:



private fun removeSpaces(s: CharSequence) {
if (s.last().isWhitespace()) {
val textWithoutSpaces = s.replace(Regex("\s"), "")
getText().clear()
append(textWithoutSpaces)
setSelection(textWithoutSpaces.length)
}
}









share|improve this question
















I have a string:



2+3-{Some value}


How can I prevent user from adding spaces between operators and operands, but allow to add spaces between curly braces? Maybe regex?



Update



I'm working on real time validating formula. All validations including whitespace removal are done using TextWatcher. My simplified code looks like this:



private val formulaWatcher: TextWatcher = object : TextWatcher {
override fun afterTextChanged(s: Editable?) = Unit

override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit

override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
//Delay used here to avoid IndexOfBoundExceptions which arise because of a setSelection() method, it works with a little delay
Handler().postDelayed({
removeSpaces(s)
}, 100)
}
}


Remove spaces function:



private fun removeSpaces(s: CharSequence) {
if (s.last().isWhitespace()) {
val textWithoutSpaces = s.replace(Regex("\s"), "")
getText().clear()
append(textWithoutSpaces)
setSelection(textWithoutSpaces.length)
}
}






java android string replace kotlin






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 13 '18 at 9:15







Skullper

















asked Nov 13 '18 at 8:54









SkullperSkullper

19611




19611








  • 1





    Please read "How to create a Minimal, Complete, and Verifiable example". Then use the edit link to improve your question (do not add more information via comments). Otherwise we are not able to answer your question and help you. Show us a complete example, and the code you have, and tell us where it deviates from your expectations.

    – GhostCat
    Nov 13 '18 at 8:55













  • Maybe regex? - gooed idea using String::replaceAll

    – Scary Wombat
    Nov 13 '18 at 8:59











  • @ScaryWombat replaceAll will replace all whitespaces in string. I need to save spaces between curly braces

    – Skullper
    Nov 13 '18 at 9:07














  • 1





    Please read "How to create a Minimal, Complete, and Verifiable example". Then use the edit link to improve your question (do not add more information via comments). Otherwise we are not able to answer your question and help you. Show us a complete example, and the code you have, and tell us where it deviates from your expectations.

    – GhostCat
    Nov 13 '18 at 8:55













  • Maybe regex? - gooed idea using String::replaceAll

    – Scary Wombat
    Nov 13 '18 at 8:59











  • @ScaryWombat replaceAll will replace all whitespaces in string. I need to save spaces between curly braces

    – Skullper
    Nov 13 '18 at 9:07








1




1





Please read "How to create a Minimal, Complete, and Verifiable example". Then use the edit link to improve your question (do not add more information via comments). Otherwise we are not able to answer your question and help you. Show us a complete example, and the code you have, and tell us where it deviates from your expectations.

– GhostCat
Nov 13 '18 at 8:55







Please read "How to create a Minimal, Complete, and Verifiable example". Then use the edit link to improve your question (do not add more information via comments). Otherwise we are not able to answer your question and help you. Show us a complete example, and the code you have, and tell us where it deviates from your expectations.

– GhostCat
Nov 13 '18 at 8:55















Maybe regex? - gooed idea using String::replaceAll

– Scary Wombat
Nov 13 '18 at 8:59





Maybe regex? - gooed idea using String::replaceAll

– Scary Wombat
Nov 13 '18 at 8:59













@ScaryWombat replaceAll will replace all whitespaces in string. I need to save spaces between curly braces

– Skullper
Nov 13 '18 at 9:07





@ScaryWombat replaceAll will replace all whitespaces in string. I need to save spaces between curly braces

– Skullper
Nov 13 '18 at 9:07












1 Answer
1






active

oldest

votes


















1














UDATE



Based on that code snippet you provided, I modified the answer.
First, use trim() function to remove spaces from the beginning and end of the input string. After trimming the string, use the following regular expression to reach the desired pattern.



private fun removeSpaces(s: CharSequence) {
// e.g. s is " 2 + 3 - { some value } "
s = s.trim()
// now s is "2 + 3 - { some value }"

// define a regex matching a pattern of characters including some spaces before and after an operator (+,-,*,/)
val re = Regex("""s*([+-*/])s*""")

// $1 denotes the group in the regex containing only an operator
val textWithoutSpaces = re.replace(s, "$1")
// textWithoutSpaces is "2+3-{ some value }"

getText().clear()
append(textWithoutSpaces)
setSelection(textWithoutSpaces.length)
}


The regex works in this way that finds each operator i.e. +,-,*,and / along with white spaces before and after it. By grouping the operator itself using parantheses, all patterns including extra spaces are replaced by only the operators without any extra spaces.






share|improve this answer





















  • 1





    thanks, but this not working. Because it's deleting spaces only from start and end. If we paste string like this: 2+ {oper 1}, we will get: 2+ {oper 1}

    – Skullper
    Nov 13 '18 at 9:11













  • From your update and comments, I think you mean 2 + 3 - { any string } must be converted to 2+3-{ any string }. Am I right?

    – Abdollah
    Nov 13 '18 at 10:43








  • 1





    yes, you're right

    – Skullper
    Nov 13 '18 at 11:58













  • @Skullper I added a regex to the solution and tested it. It works fine.

    – Abdollah
    Nov 13 '18 at 18:07











  • @Abdolah Wow, thank you it really helps. I have tried regex with look-ahead, but your solution is more sophisticated)

    – Skullper
    Nov 13 '18 at 18:22











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53277138%2fhow-can-i-replace-specified-whitespaces-in-string%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














UDATE



Based on that code snippet you provided, I modified the answer.
First, use trim() function to remove spaces from the beginning and end of the input string. After trimming the string, use the following regular expression to reach the desired pattern.



private fun removeSpaces(s: CharSequence) {
// e.g. s is " 2 + 3 - { some value } "
s = s.trim()
// now s is "2 + 3 - { some value }"

// define a regex matching a pattern of characters including some spaces before and after an operator (+,-,*,/)
val re = Regex("""s*([+-*/])s*""")

// $1 denotes the group in the regex containing only an operator
val textWithoutSpaces = re.replace(s, "$1")
// textWithoutSpaces is "2+3-{ some value }"

getText().clear()
append(textWithoutSpaces)
setSelection(textWithoutSpaces.length)
}


The regex works in this way that finds each operator i.e. +,-,*,and / along with white spaces before and after it. By grouping the operator itself using parantheses, all patterns including extra spaces are replaced by only the operators without any extra spaces.






share|improve this answer





















  • 1





    thanks, but this not working. Because it's deleting spaces only from start and end. If we paste string like this: 2+ {oper 1}, we will get: 2+ {oper 1}

    – Skullper
    Nov 13 '18 at 9:11













  • From your update and comments, I think you mean 2 + 3 - { any string } must be converted to 2+3-{ any string }. Am I right?

    – Abdollah
    Nov 13 '18 at 10:43








  • 1





    yes, you're right

    – Skullper
    Nov 13 '18 at 11:58













  • @Skullper I added a regex to the solution and tested it. It works fine.

    – Abdollah
    Nov 13 '18 at 18:07











  • @Abdolah Wow, thank you it really helps. I have tried regex with look-ahead, but your solution is more sophisticated)

    – Skullper
    Nov 13 '18 at 18:22
















1














UDATE



Based on that code snippet you provided, I modified the answer.
First, use trim() function to remove spaces from the beginning and end of the input string. After trimming the string, use the following regular expression to reach the desired pattern.



private fun removeSpaces(s: CharSequence) {
// e.g. s is " 2 + 3 - { some value } "
s = s.trim()
// now s is "2 + 3 - { some value }"

// define a regex matching a pattern of characters including some spaces before and after an operator (+,-,*,/)
val re = Regex("""s*([+-*/])s*""")

// $1 denotes the group in the regex containing only an operator
val textWithoutSpaces = re.replace(s, "$1")
// textWithoutSpaces is "2+3-{ some value }"

getText().clear()
append(textWithoutSpaces)
setSelection(textWithoutSpaces.length)
}


The regex works in this way that finds each operator i.e. +,-,*,and / along with white spaces before and after it. By grouping the operator itself using parantheses, all patterns including extra spaces are replaced by only the operators without any extra spaces.






share|improve this answer





















  • 1





    thanks, but this not working. Because it's deleting spaces only from start and end. If we paste string like this: 2+ {oper 1}, we will get: 2+ {oper 1}

    – Skullper
    Nov 13 '18 at 9:11













  • From your update and comments, I think you mean 2 + 3 - { any string } must be converted to 2+3-{ any string }. Am I right?

    – Abdollah
    Nov 13 '18 at 10:43








  • 1





    yes, you're right

    – Skullper
    Nov 13 '18 at 11:58













  • @Skullper I added a regex to the solution and tested it. It works fine.

    – Abdollah
    Nov 13 '18 at 18:07











  • @Abdolah Wow, thank you it really helps. I have tried regex with look-ahead, but your solution is more sophisticated)

    – Skullper
    Nov 13 '18 at 18:22














1












1








1







UDATE



Based on that code snippet you provided, I modified the answer.
First, use trim() function to remove spaces from the beginning and end of the input string. After trimming the string, use the following regular expression to reach the desired pattern.



private fun removeSpaces(s: CharSequence) {
// e.g. s is " 2 + 3 - { some value } "
s = s.trim()
// now s is "2 + 3 - { some value }"

// define a regex matching a pattern of characters including some spaces before and after an operator (+,-,*,/)
val re = Regex("""s*([+-*/])s*""")

// $1 denotes the group in the regex containing only an operator
val textWithoutSpaces = re.replace(s, "$1")
// textWithoutSpaces is "2+3-{ some value }"

getText().clear()
append(textWithoutSpaces)
setSelection(textWithoutSpaces.length)
}


The regex works in this way that finds each operator i.e. +,-,*,and / along with white spaces before and after it. By grouping the operator itself using parantheses, all patterns including extra spaces are replaced by only the operators without any extra spaces.






share|improve this answer















UDATE



Based on that code snippet you provided, I modified the answer.
First, use trim() function to remove spaces from the beginning and end of the input string. After trimming the string, use the following regular expression to reach the desired pattern.



private fun removeSpaces(s: CharSequence) {
// e.g. s is " 2 + 3 - { some value } "
s = s.trim()
// now s is "2 + 3 - { some value }"

// define a regex matching a pattern of characters including some spaces before and after an operator (+,-,*,/)
val re = Regex("""s*([+-*/])s*""")

// $1 denotes the group in the regex containing only an operator
val textWithoutSpaces = re.replace(s, "$1")
// textWithoutSpaces is "2+3-{ some value }"

getText().clear()
append(textWithoutSpaces)
setSelection(textWithoutSpaces.length)
}


The regex works in this way that finds each operator i.e. +,-,*,and / along with white spaces before and after it. By grouping the operator itself using parantheses, all patterns including extra spaces are replaced by only the operators without any extra spaces.







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 13 '18 at 18:13

























answered Nov 13 '18 at 9:07









AbdollahAbdollah

10011




10011








  • 1





    thanks, but this not working. Because it's deleting spaces only from start and end. If we paste string like this: 2+ {oper 1}, we will get: 2+ {oper 1}

    – Skullper
    Nov 13 '18 at 9:11













  • From your update and comments, I think you mean 2 + 3 - { any string } must be converted to 2+3-{ any string }. Am I right?

    – Abdollah
    Nov 13 '18 at 10:43








  • 1





    yes, you're right

    – Skullper
    Nov 13 '18 at 11:58













  • @Skullper I added a regex to the solution and tested it. It works fine.

    – Abdollah
    Nov 13 '18 at 18:07











  • @Abdolah Wow, thank you it really helps. I have tried regex with look-ahead, but your solution is more sophisticated)

    – Skullper
    Nov 13 '18 at 18:22














  • 1





    thanks, but this not working. Because it's deleting spaces only from start and end. If we paste string like this: 2+ {oper 1}, we will get: 2+ {oper 1}

    – Skullper
    Nov 13 '18 at 9:11













  • From your update and comments, I think you mean 2 + 3 - { any string } must be converted to 2+3-{ any string }. Am I right?

    – Abdollah
    Nov 13 '18 at 10:43








  • 1





    yes, you're right

    – Skullper
    Nov 13 '18 at 11:58













  • @Skullper I added a regex to the solution and tested it. It works fine.

    – Abdollah
    Nov 13 '18 at 18:07











  • @Abdolah Wow, thank you it really helps. I have tried regex with look-ahead, but your solution is more sophisticated)

    – Skullper
    Nov 13 '18 at 18:22








1




1





thanks, but this not working. Because it's deleting spaces only from start and end. If we paste string like this: 2+ {oper 1}, we will get: 2+ {oper 1}

– Skullper
Nov 13 '18 at 9:11







thanks, but this not working. Because it's deleting spaces only from start and end. If we paste string like this: 2+ {oper 1}, we will get: 2+ {oper 1}

– Skullper
Nov 13 '18 at 9:11















From your update and comments, I think you mean 2 + 3 - { any string } must be converted to 2+3-{ any string }. Am I right?

– Abdollah
Nov 13 '18 at 10:43







From your update and comments, I think you mean 2 + 3 - { any string } must be converted to 2+3-{ any string }. Am I right?

– Abdollah
Nov 13 '18 at 10:43






1




1





yes, you're right

– Skullper
Nov 13 '18 at 11:58







yes, you're right

– Skullper
Nov 13 '18 at 11:58















@Skullper I added a regex to the solution and tested it. It works fine.

– Abdollah
Nov 13 '18 at 18:07





@Skullper I added a regex to the solution and tested it. It works fine.

– Abdollah
Nov 13 '18 at 18:07













@Abdolah Wow, thank you it really helps. I have tried regex with look-ahead, but your solution is more sophisticated)

– Skullper
Nov 13 '18 at 18:22





@Abdolah Wow, thank you it really helps. I have tried regex with look-ahead, but your solution is more sophisticated)

– Skullper
Nov 13 '18 at 18:22


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53277138%2fhow-can-i-replace-specified-whitespaces-in-string%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

List item for chat from Array inside array React Native

Thiostrepton

Caerphilly