Instead of focusing on what 2 spaces isn't, use a negative look ahead for what it is:
^(?!.* ).+
Or if the 1st and last must be non-spaces (not stated):
^\S((?!.* ).*\S)?$
Which also allows exactly 1 non-space as the entire input.
The primary thing that makes this work is this expression ^(?!.* ), which a negative look-ahead (?!.* ) anchored to start of input by ^. It asserts, without consuming input, that the text that follows the current point does not match the given expression, in this case ".* " (quotes added for clarity), which is "anything then two spaces". In other words "two spaces do not appear at any point after here".
The second option could have been written ^\S(?!.* ).*\S$ - that same as the first but with \S at either end, but that would require different characters at each end because \S consumes input, so it wouldn't match a single letter eg "X". My making all characters other than the first optional, it allows the single character to pass (as per your requirements), while retaining the prevention of two spaces.
Instead of focusing on what 2 spaces isn't, use a negative look ahead for what it is:
^(?!.* ).+
Or if the 1st and last must be non-spaces (not stated):
^\S((?!.* ).*\S)?$
Which also allows exactly 1 non-space as the entire input.
The primary thing that makes this work is this expression ^(?!.* ), which a negative look-ahead (?!.* ) anchored to start of input by ^. It asserts, without consuming input, that the text that follows the current point does not match the given expression, in this case ".* " (quotes added for clarity), which is "anything then two spaces". In other words "two spaces do not appear at any point after here".
The second option could have been written ^\S(?!.* ).*\S$ - that same as the first but with \S at either end, but that would require different characters at each end because \S consumes input, so it wouldn't match a single letter eg "X". My making all characters other than the first optional, it allows the single character to pass (as per your requirements), while retaining the prevention of two spaces.
You can use something like that
^(\S\s{0,1})*\S$
Hi, fairly new to Java here. In a project I’m doing, part of it requires me to split up a line read from a file and store each part in an array for later use (well it’s not required per say but it’s the way I’m doing it), and I’d like to use regex to do it. The file reading part is all fine, the thing is, the line I’m reading is split up by multiple spaces (required in the project specification), so it’s like: [Thing A] [Thing B] [Thing C] and so on, each line has letters, numbers and slashes.
I’ve been looking through Stack Overflow, YouTube, other sites and such and I haven’t found anything that works exactly as I need it to. The main 3 things I remembered trying that I found were \\s\\s, \\s+ and \\s{2} but none of those worked for me, \\s+ works for one or more spaces, but I need it to exclusively be more than one space. Using my previous example, [Thing C] is a full name, so if I did it for only one space then the name would get split up, which I need to avoid. Point being: is there any way for me to use the regex and split features that lets me split up the parts of the string separated by 2 spaces? So like:
String line = “Insert line here”;
String regex = “[x]”; (with “x“ being a placeholder)
String[] array = line.split(regex);
Something like that? If there‘s no way to do it like that then I’m open to using other ideas. (Also sorry, I couldn’t figure out how to get the code block to work)
Example: My Name is Mohit. Surname is Kumar.
The regex should only match the spaces after is as there are multiple spaces after it, but not after other words as there is only one space after them and not after Mohit. as there is a period after the word.
I have tried
-
(?<!\.)\s{2,} - https://regex101.com/r/jAkQM1/1
-
(?<!\.)\s+ - https://regex101.com/r/PfYX26/1
but both these expressions are matching multiple spaces after Mohit. expect for the first space. I'm testing my regex at Regex101.
Thanks for the help.
Given that you also want to cover tabs, newlines, etc, just replace \s\s+ with ' ':
string = string.replace(/\s\s+/g, ' ');
If you really want to cover only spaces (and thus not tabs, newlines, etc), do so:
string = string.replace(/ +/g, ' ');
Since you seem to be interested in performance, I profiled these with firebug. Here are the results I got:
str.replace( / +/g, ' ' ) -> 380ms
str.replace( /\s\s+/g, ' ' ) -> 390ms
str.replace( / {2,}/g, ' ' ) -> 470ms
str.replace( / +/g, ' ' ) -> 790ms
str.replace( / +(?= )/g, ' ') -> 3250ms
This is on Firefox, running 100k string replacements.
I encourage you to do your own profiling tests with firebug, if you think performance is an issue. Humans are notoriously bad at predicting where the bottlenecks in their programs lie.
(Also, note that IE 8's developer toolbar also has a profiler built in -- it might be worth checking what the performance is like in IE.)
How do I replace any number of spaces using regular expressions
Notepad++ Solution
To match one or more space characters:
- Set "Find what" to
+(space followed by +)
To match one of more whitespace characters (space, EOL, and tab all count as whitespace):
Set "Find what" to
\s+Warning: Using
\s+will match end of line and therefore join multiple lines together (separated by the "replace with" string)
To replace with a tab character:
- Set "Replace with" to
\t
To enable regular expression (so the above special codes will work)
- Select "Regular expression".

Source How to use regular expressions in Notepad++ (tutorial)
Taken from here:
Use as "find" expression:
{1,}
namely a space followed by {1,}.
To replace with tab, enter ^t in the replace box. Don't forget to activate regular expressions.
This link covers the syntax of the given regex. Below is an extract of a relevant part.
{n,} Matches when the preceding character occurs at least n times, for example, ba{2,}b will find 'baab', 'baaab' or 'baaaab' but NOT 'bab'. Values are enclosed in braces (curly brackets).
For the records, it has been tested on notepad++ (See here, courtesy of barlop). You can also put a \t in the replace box.
Probably match it again against /\s\s/.
You can check for two consecutive spaces by using the repetition regex. i.e If you want to match a regex which repeats say between 1 to 12 times, you can give,
regex{1, 12}
Similarly, if u want to match a space which repeats just two times and not more or less than that, you can give
\s{2}
Remember that this is a general way of checking the repeat patterns. The numbers in curly braces will always try to see the number of repetitions which the previous regex has.
cheers!
The simplest solution is to split on \s{2,} to get the "words" you want, but if you insist on scanning for the tokens, then where as before you have \S+, what you have now is \S+(\s\S+)*. That's exactly what it says: \S+, followed by zero or more (\s\S+). You can use non-capturing group for performance, i.e. \S+(?:\s\S+)*. You can even make each repetition possessive if your flavor supports it for extra boost, i.e. \S++(?:\s\S++)*+.
Here's a Java snippet to demonstrate:
String text = "AB C DE FG HIJ KLM NO P QRST";
Matcher m = Pattern.compile("\\S++(?:\\s\\S++)*+").matcher(text);
while (m.find()) {
System.out.println("[" + m.group() + "]");
}
This prints:
[AB C]
[DE]
[FG HIJ]
[KLM]
[NO]
[P]
[QRST]
You can of course substitute just the space character instead of \s if that's your requirement.
References
- regular-expressions.info/Character Class, Brackets for Grouping, Repetition, Possessive
if you know what the delimiter is (\s\s+), you could split instead of match. Simply split on two or more spaces.
Regards
rbo