How to Keep the Spaces at the End And/Or at the Beginning of a String

How to keep the spaces at the end and/or at the beginning of a String?

Even if you use string formatting, sometimes you still need white spaces at the beginning or the end of your string. For these cases, neither escaping with \, nor xml:space attribute helps. You must use HTML entity   for a whitespace.

Use   for non-breakable whitespace.

Use for regular space.

how to keep space at the start and/or end of a string using split

The current (?<=[)])\s*|\s*(?=[(]) regex matches 0+ whitespaces with \s*, and that is why they are missing.

You might just remove \s* from the regex, and (?<=[)])|(?=[(]) should already work in most cases.

However, you may use other approaches where you can control what (...) substrings you split out.

For example, you may use (\([^()]*\)) regex:

var output = Regex
.Split(input, @"(\([^()]*\))")
.Where(s => !string.IsNullOrEmpty(s))
.ToList();

It will match and capture substrings inside parentheses and thus the matches will also be part of the resulting list.

See the online C# demo and the online regex demo.

Split list:

enter image description here

NOTE: To split out substrings between balanced parentheses, use

@"(\((?>[^()]+|(?<c>)\(|(?<-c>)\))*\)(?(c)(?!)))"

See another C# demo. See this answer for this regex description. More on this can be found at the regular-expressions.info Balancing Groups.

Python: Keeping whitespace at the beginning of a string

You can do:

new_string = old_string[:-len(old_string.lstrip())] + 'new text'

Or if you prefer str.format:

new_string = '{}new text'.format(old_string[:-len(old_string.lstrip())])

Regex: Specify space or start of string and space or end of string

You can use any of the following:

\b      #A word break and will work for both spaces and end of lines.
(^|\s) #the | means or. () is a capturing group.

/\b(stackoverflow)\b/

Also, if you don't want to include the space in your match, you can use lookbehind/aheads.

(?<=\s|^)         #to look behind the match
(stackoverflow) #the string you want. () optional
(?=\s|$) #to look ahead.

removing white spaces at beginning and end of string

Your string contains not only whitespace but also new line characters.

Use stringByTrimmingCharactersInSet with whitespaceAndNewlineCharacterSet.

let string = "\r\n\t- Someone will come here?\n- I don't know for sure...\r\n\r\n"
let trimmedString = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

In Swift 3 it's more cleaned up:

let trimmedString = string.trimmingCharacters(in: .whitespacesAndNewlines)

How to remove only trailing spaces of a string in Java and keep leading spaces?

Since JDK 11

If you are on JDK 11 or higher you should probably be using stripTrailing().


Earlier JDK versions

Using the regular expression \s++$, you can replace all trailing space characters (includes space and tab characters) with the empty string ("").

final String text = "  foo   ";
System.out.println(text.replaceFirst("\\s++$", ""));

Output

  foo

Online demo.

Here's a breakdown of the regex:

  • \s – any whitespace character,
  • ++ – match one or more of the previous token (possessively); i.e., match one or more whitespace character. The + pattern is used in its possessive form ++, which takes less time to detect the case when the pattern does not match.
  • $ – the end of the string.

Thus, the regular expression will match as much whitespace as it can that is followed directly by the end of the string: in other words, the trailing whitespace.

The investment into learning regular expressions will become more valuable, if you need to extend your requirements later on.

References

  • Java regular expression syntax

How to put space character into a string name in XML?

to use white space in xml as string use  . XML won't take white space as it is. it will trim the white space before setting it. So use   instead of single white space

Enforcing spaces in string resources

Did you try to surround your string with quotes? Maybe leading and trailing whitespaces are stripped automatically.

<string name="foo">" bar"</string>

See the example at https://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling in section "Escaping apostrophes and quotes".

How to add leading white space (spaces) in TextView (Android)

use this below method to add space before text.

textView.setText("     "+"328");


Related Topics



Leave a reply



Submit