RegEx for ["abc", ["123", "cba"]] - java

I'm not strong in regex, so any help would be appreciated.
I need to parse such strings:
["text", "text", ["text",["text"]],"text"]
And output should be (4 strings):
text, text, ["text",["text"]], text
I've tried this pattern (\\[[^\\[,^\\]]*\\])|(\"([^\"]*)\"):
String data="\"aa\", \"aaa\", [\"bb\", [\"1\",\"2\"]], [cc]";
Pattern p=Pattern.compile("(\\[[^\\[,^\\]]*\\])|(\"([^\"]*)\")");
But output is (quotes themselves in output are not so critical):
"aa", "aaa", "bb", "1", "2", [cc]
How to improve my regex?

I'm not sure regex are able to do that kind of stuff on their own. Here is a way to do it though:
// data string
String input = "\"aa\", \"a, aa\", [\"bb\", [\"1\", \"2\"]], [cc], [\"dd\", [\"5\"]]";
System.out.println(input);
// char that can't ever be within the data string
char tempReplacement = '#';
// escape strings containing commas, e.g "hello, world", ["x, y", 42]
while(input.matches(".*\"[^\"\\[\\]]+,[^\"\\[\\]]+\".*")) {
input = input.replaceAll("(\"[^\"\\[\\]]+),([^\"\\[\\]]+\")", "$1" + tempReplacement + "$2");
}
// while there are "[*,*]" substrings
while(input.matches(".*\\[[^\\]]+,[^\\]]+\\].*")) {
// replace the nested "," chars by the replacement char
input = input.replaceAll("(\\[[^\\]]+),([^\\]]+\\])", "$1" + tempReplacement + "$2");
}
// split the string by the remaining "," (i.e. those non nested)
String[] split = input.split(",");
List<String> output = new LinkedList<String>();
for(String s : split) {
// replace all the replacement chars by a ","
s = s.replaceAll(tempReplacement + "", ",");
s = s.trim();
output.add(s);
}
// syso
System.out.println("SPLIT:");
for(String s : output) {
System.out.println("\t" + s);
}
Output:
"aa", "a, aa", ["bb", ["1", "2"]], [cc], ["dd", ["5"]]
SPLIT:
"aa"
"a, aa"
["bb", ["1","2"]]
[cc]
["dd", ["5"]]
PS: the code seems complex 'cause commented. Here is a more concise version:
public static List<String> split(String input, char tempReplacement) {
while(input.matches(".*\"[^\"\\[\\]]+,[^\"\\[\\]]+\".*")) {
input = input.replaceAll("(\"[^\"\\[\\]]+),([^\"\\[\\]]+\")", "$1" + tempReplacement + "$2");
}
while(input.matches(".*\\[[^\\]]+,[^\\]]+\\].*")) {
input = input.replaceAll("(\\[[^\\]]+),([^\\]]+\\])", "$1" + tempReplacement + "$2");
}
String[] split = input.split(",");
List<String> output = new LinkedList<String>();
for(String s : split) {
output.add(s.replaceAll(tempReplacement + "", ",").trim());
}
return output;
}
Call:
String input = "\"aa\", \"a, aa\", [\"bb\", [\"1\", \"2\"]], [cc], [\"dd\", [\"5\"]]";
List<String> output = split(input, '#');

It seems that you have recursion in your input, so if you have many nested [] regexes are probably not the best solution.
For this purpose I think it's far better/easier to use simple algorithm using indexOf() and substring(). It's also aften more efficient!

Unfortunately i don't think you can do that with Java regexes. What you have here is recursive expression.. This type of language is not amendable to basic regular expressions (which is what java Pattern actually is).
But it's not that hard to write a small recursive descent parser for that language.
You can check to following answer for inspiration: java method for parsing nested expressions

Related

Separate string by whitespace, but keep newlines in split array

I'm trying to split a string in Java, but keep the newline characters as elements in the array.
For example, with input: "Hello \n\n\nworld!"
I want the output to be: ["Hello", "\n", "\n", "\n", "world", "!"]
The regex I have in place right now is this:
String[] parsed = input.split(" +|(?=\\p{Punct})|(?<=\\p{Punct})");
This gets me the punctuation separation I want, but its output looks like this:["Hello", "\n\n\nworld", "!"]
Is there a way to unclump the newlines in Java?
You could first replace all \n with \n (newline and a space) and then do a simple split on the space character.
String input = "Hello \n\n\nworld!";
String replacement = input.replace("\n", "\n ");
String[] result = replacement.split(" ");
input: "Hello \n\n\nworld!"
replacement: "Hello \n \n \n world!"
result: ["Hello", "\n", "\n", "\n", "world!"]
Note: my example does not handle the final exclamation mark - but it seems you already know how to handle that.
The trick is to add whitespace after each "\n" and then apply your regex.
String line = "Hello \n\n\nworld!";
line = line.replaceAll("\n", "\n "); // here we replace all "\n" to "\n "
String[] items = line.split(" +|(?=\\p{Punct})|(?<=\\p{Punct})");
or shorter version:
String line = "Hello \n\n\nworld!";
String[] items = line.replaceAll("\n", "\n ").split(" +|(?=\\p{Punct})|(?<=\\p{Punct})");
So, in this context the result is: ["Hello", "\n", "\n", "\n", "world", "!"]
Using the find method makes things easier:
String str = "Hello \n\n\nworld!";
List<String> myList = new ArrayList<String>();
Pattern pat = Pattern.compile("\\w+|\\H");
Matcher m = pat.matcher(str);
while (m.find()) {
myList.add(m.group(0));
}
If you use Java 7, change \\H to [\\S\\n].
Note that using this approach, you obtain a pattern easier to write and to edit since you don't need to use lookarounds.

How to split String before first comma?

I have an overriding method with String which returns String in format of:
"abc,cde,def,fgh"
I want to split the string content into two parts:
String before first comma and
String after first comma
My overriding method is :
#Override
protected void onPostExecute(String addressText) {
placeTitle.setText(addressText);
}
Now how do I split the string into two parts, so that I can use them to set the text in two different TextView?
You may use the following code snippet
String str ="abc,cde,def,fgh";
String kept = str.substring( 0, str.indexOf(","));
String remainder = str.substring(str.indexOf(",")+1, str.length());
String splitted[] =s.split(",",2); // will be matched 1 times.
splitted[0] //before the first comma. `abc`
splitted[1] //the whole String after the first comma. `cde,def,fgh`
If you want only cde as the string after first comma.
Then you can use
String splitted[] =s.split(",",3); // will be matched 2 times
or without the limit
String splitted[] =s.split(",");
Don't forget to check the length to avoid ArrayIndexOutOfBound.
The below is what you are searching for:
public String[] split(",", 2)
This will give 2 string array. Split has two versions. What you can try is
String str = "abc,def,ghi,jkl";
String [] twoStringArray= str.split(",", 2); //the main line
System.out.println("String befor comma = "+twoStringArray[0]);//abc
System.out.println("String after comma = "+twoStringArray[1]);//def,ghi,jkl
String s =" abc,cde,def,fgh";
System.out.println("subString1="+ s.substring(0, s.indexOf(",")));
System.out.println("subString2="+ s.substring(s.indexOf(",") + 1, s.length()));
// Note the use of limit to prevent it from splitting into more than 2 parts
String [] parts = s.split(",", 2);
// ...setText(parts[0]);
// ...setText(parts[1]);
For more information, refer to this documentation.
Use split with regex:
String splitted[] = addressText.split(",",2);
System.out.println(splitted[0]);
System.out.println(splitted[1]);
:In this case you can use replaceAll with some regex to get this input so you can use :
System.out.println("test another :::"+test.replaceAll("(\\.*?),.*", "$1"));
If the key is just an String you can use (\\D?),.*
System.out.println("test ::::"+test.replaceAll("(\\D?),.*", "$1"));
From jse1.4String - Two split methods are new. The subSequence method has been added, as required by the CharSequence interface that String now implements. Three additional methods have been added: matches, replaceAll, and replaceFirst.
Using Java String.split(String regex, int limit) with Pattern.quote(String s)
The string "boo:and:foo", for example, yields the following results with these parameters:
Regex Limit Result
: 2 { "boo", "and:foo" }
: 5 { "boo", "and", "foo" }
: -2 { "boo", "and", "foo" }
o 5 { "b", "", ":and:f", "", "" }
o -2 { "b", "", ":and:f", "", "" }
o 0 { "b", "", ":and:f" }
String str = "abc?def,ghi?jkl,mno,pqr?stu,vwx?yz";
String quotedText = Pattern.quote( "?" );
// ? - \\? we have to escape sequence of some characters, to avoid use Pattern.quote( "?" );
String[] split = str.split(quotedText, 2); // ["abc", "def,ghi?jkl,mno,pqr?stu,vwx?yz"]
for (String string : split) {
System.out.println( string );
}
I have face the same problem in URL parameters, To resoleve it i need to split based on first ? So that the remaing String contains parameter values and they need to be split based on &.
String paramUrl = "https://www.google.co.in/search?q=encode+url&oq=encode+url";
String subURL = URLEncoder.encode( paramUrl, "UTF-8");
String myMainUrl = "http://example.com/index.html?url=" + subURL +"&name=chrome&version=56";
System.out.println("Main URL : "+ myMainUrl );
String decodeMainURL = URLDecoder.decode(myMainUrl, "UTF-8");
System.out.println("Main URL : "+ decodeMainURL );
String[] split = decodeMainURL.split(Pattern.quote( "?" ), 2);
String[] Parameters = split[1].split("&");
for (String param : Parameters) {
System.out.println( param );
}
Run Javascript on the JVM with Rhino/Nashorn « With JavaScript’s String.prototype.split function:
var str = "abc?def,ghi?jkl,mno,pqr?stu,vwx?yz";
var parts = str.split(',');
console.log( parts ); // (5) ["abc?def", "ghi?jkl", "mno", "pqr?stu", "vwx?yz"]
console.log( str.split('?') ); // (5) ["abc", "def,ghi", "jkl,mno,pqr", "stu,vwx", "yz"]
var twoparts = str.split(/,(.+)/);
console.log( parts ); // (3) ["abc?def", "ghi?jkl,mno,pqr?stu,vwx?yz", ""]
console.log( str.split(/\?(.+)/) ); // (3) ["abc", "def,ghi?jkl,mno,pqr?stu,vwx?yz", ""]
public static int[] **stringToInt**(String inp,int n)
{
**int a[]=new int[n];**
int i=0;
for(i=0;i<n;i++)
{
if(inp.indexOf(",")==-1)
{
a[i]=Integer.parseInt(inp);
break;
}
else
{
a[i]=Integer.parseInt(inp.substring(0, inp.indexOf(",")));
inp=inp.substring(inp.indexOf(",")+1,inp.length());
}
}
return a;
}
I created this function. Arguments are input string (String inp, here) and integer value(int n, here), which is the size of an array which contains values in string separated by commas. You can use other special character to extract values from string containing that character. This function will return array of integer of size n.
To use,
String inp1="444,55";
int values[]=stringToInt(inp1,2);

Replace a character with different characters depending on which character it is

I have searched SO (and Google) but not found any fully matching answer to my question:
I want to replace all swedish characters and whitespace in a String with another character. I would like it to work as follows:
"å" and "ä" should be replaced with "a"
"ö" should be replaced with "o"
"Å" and "Ä" should be replace with "A"
"Ö" should be replaced with "O"
" " should be replaced with "-"
Can this be achieved with regex (or any other way), and if so, how?
Of course, the below method does the job (and can be improved, I know, by replacing for example "å" and "ä" on the same line):
private String changeSwedishCharactersAndWhitespace(String string) {
String newString = string.replaceAll("å", "a");
newString = string.replaceAll("ä", "a");
newString = string.replaceAll("ö", "o");
newString = string.replaceAll("Å", "A");
newString = string.replaceAll("Ä", "A");
newString = string.replaceAll("Ö", "O");
newString = string.replaceAll(" ", "-");
return newString;
}
I know how to use regex to replace, for example, all "å", "ä", or "ö" with "". The question is how do I replace a character using regex with another depending on which character it is? There must surely be a better way using regex than the above aproach?
For latin characters with diacritics, a unicode normalization (java text) to retrieve basic letter code + diacritic combining code might help. Something like:
import java.text.Normalizer;
newString = Normalizer.normalize(string,
Normalizer.Form.NFKD).replaceAll("\\p{M}", "");
You can use StringUtils.replaceEach, like this:
private String changeSwedishCharactersAndWhitespace(String string) {
String newString = StringUtils.replaceEach (string,
new String[] {"å", "ä", "ö", "Å", "Ä", "Ö", " "},
new String[] {"a", "a", "o", "A", "A", "O", "-"});
return newString;
}
I think there is not a common regex for replacing these characters at once. Apart from that, you can facilitate your replacement work by using a HashMap.
HashMap<String, String> map = new HashMap<String, String>()
{{put("ä", "a"); /*put others*/}};
for (Map.Entry<String, String> entry : map.entrySet())
newString = string.replaceAll(entry.getKey(), entry.getValue());
You can write your own mapper usen the matcher.find method:
public static void main(String[] args) {
String from = "äöÂ";
String to = "aoA";
String testString = "Hellö Wärld";
Pattern p = Pattern.compile(String.format("[%s]", from));
Matcher m = p.matcher(testString);
String result = testString;
while (m.find()){
char charFound = m.group(0).charAt(0);
result = result.replace(charFound, to.charAt(from.indexOf(charFound)));
}
System.out.println(result);
}
this will replace
Hellö Wärld
with
Hello Warld

Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces

Looking for quick, simple way in Java to change this string
" hello there "
to something that looks like this
"hello there"
where I replace all those multiple spaces with a single space, except I also want the one or more spaces at the beginning of string to be gone.
Something like this gets me partly there
String mytext = " hello there ";
mytext = mytext.replaceAll("( )+", " ");
but not quite.
Try this:
String after = before.trim().replaceAll(" +", " ");
See also
String.trim()
Returns a copy of the string, with leading and trailing whitespace omitted.
regular-expressions.info/Repetition
No trim() regex
It's also possible to do this with just one replaceAll, but this is much less readable than the trim() solution. Nonetheless, it's provided here just to show what regex can do:
String[] tests = {
" x ", // [x]
" 1 2 3 ", // [1 2 3]
"", // []
" ", // []
};
for (String test : tests) {
System.out.format("[%s]%n",
test.replaceAll("^ +| +$|( )+", "$1")
);
}
There are 3 alternates:
^_+ : any sequence of spaces at the beginning of the string
Match and replace with $1, which captures the empty string
_+$ : any sequence of spaces at the end of the string
Match and replace with $1, which captures the empty string
(_)+ : any sequence of spaces that matches none of the above, meaning it's in the middle
Match and replace with $1, which captures a single space
See also
regular-expressions.info/Anchors
You just need a:
replaceAll("\\s{2,}", " ").trim();
where you match one or more spaces and replace them with a single space and then trim whitespaces at the beginning and end (you could actually invert by first trimming and then matching to make the regex quicker as someone pointed out).
To test this out quickly try:
System.out.println(new String(" hello there ").trim().replaceAll("\\s{2,}", " "));
and it will return:
"hello there"
Use the Apache commons StringUtils.normalizeSpace(String str) method. See docs here
This worked perfectly for me : sValue = sValue.trim().replaceAll("\\s+", " ");
trim() method removes the leading and trailing spaces and using replaceAll("regex", "string to replace") method with regex "\s+" matches more than one space and will replace it with a single space
myText = myText.trim().replaceAll("\\s+"," ");
The following code will compact any whitespace between words and remove any at the string's beginning and end
String input = "\n\n\n a string with many spaces, \n"+
" a \t tab and a newline\n\n";
String output = input.trim().replaceAll("\\s+", " ");
System.out.println(output);
This will output a string with many spaces, a tab and a newline
Note that any non-printable characters including spaces, tabs and newlines will be compacted or removed
For more information see the respective documentation:
String#trim() method
String#replaceAll(String regex, String replacement) method
For information about Java's regular expression implementation see the documentation of the Pattern class
"[ ]{2,}"
This will match more than one space.
String mytext = " hello there ";
//without trim -> " hello there"
//with trim -> "hello there"
mytext = mytext.trim().replaceAll("[ ]{2,}", " ");
System.out.println(mytext);
OUTPUT:
hello there
To eliminate spaces at the beginning and at the end of the String, use String#trim() method. And then use your mytext.replaceAll("( )+", " ").
You can first use String.trim(), and then apply the regex replace command on the result.
Try this one.
Sample Code
String str = " hello there ";
System.out.println(str.replaceAll("( +)"," ").trim());
OUTPUT
hello there
First it will replace all the spaces with single space. Than we have to supposed to do trim String because Starting of the String and End of the String it will replace the all space with single space if String has spaces at Starting of the String and End of the String So we need to trim them. Than you get your desired String.
String blogName = "how to do in java . com";
String nameWithProperSpacing = blogName.replaceAll("\\\s+", " ");
trim()
Removes only the leading & trailing spaces.
From Java Doc,
"Returns a string whose value is this string, with any leading and trailing whitespace removed."
System.out.println(" D ev Dum my ".trim());
"D ev Dum my"
replace(), replaceAll()
Replaces all the empty strings in the word,
System.out.println(" D ev Dum my ".replace(" ",""));
System.out.println(" D ev Dum my ".replaceAll(" ",""));
System.out.println(" D ev Dum my ".replaceAll("\\s+",""));
Output:
"DevDummy"
"DevDummy"
"DevDummy"
Note: "\s+" is the regular expression similar to the empty space character.
Reference : https://www.codedjava.com/2018/06/replace-all-spaces-in-string-trim.html
In Kotlin it would look like this
val input = "\n\n\n a string with many spaces, \n"
val cleanedInput = input.trim().replace(Regex("(\\s)+"), " ")
A lot of correct answers been provided so far and I see lot of upvotes. However, the mentioned ways will work but not really optimized or not really readable.
I recently came across the solution which every developer will like.
String nameWithProperSpacing = StringUtils.normalizeSpace( stringWithLotOfSpaces );
You are done.
This is readable solution.
You could use lookarounds also.
test.replaceAll("^ +| +$|(?<= ) ", "");
OR
test.replaceAll("^ +| +$| (?= )", "")
<space>(?= ) matches a space character which is followed by another space character. So in consecutive spaces, it would match all the spaces except the last because it isn't followed by a space character. This leaving you a single space for consecutive spaces after the removal operation.
Example:
String[] tests = {
" x ", // [x]
" 1 2 3 ", // [1 2 3]
"", // []
" ", // []
};
for (String test : tests) {
System.out.format("[%s]%n",
test.replaceAll("^ +| +$| (?= )", "")
);
}
See String.replaceAll.
Use the regex "\s" and replace with " ".
Then use String.trim.
String str = " hello world"
reduce spaces first
str = str.trim().replaceAll(" +", " ");
capitalize the first letter and lowercase everything else
str = str.substring(0,1).toUpperCase() +str.substring(1,str.length()).toLowerCase();
you should do it like this
String mytext = " hello there ";
mytext = mytext.replaceAll("( +)", " ");
put + inside round brackets.
String str = " this is string ";
str = str.replaceAll("\\s+", " ").trim();
This worked for me
scan= filter(scan, " [\\s]+", " ");
scan= sac.trim();
where filter is following function and scan is the input string:
public String filter(String scan, String regex, String replace) {
StringBuffer sb = new StringBuffer();
Pattern pt = Pattern.compile(regex);
Matcher m = pt.matcher(scan);
while (m.find()) {
m.appendReplacement(sb, replace);
}
m.appendTail(sb);
return sb.toString();
}
The simplest method for removing white space anywhere in the string.
public String removeWhiteSpaces(String returnString){
returnString = returnString.trim().replaceAll("^ +| +$|( )+", " ");
return returnString;
}
check this...
public static void main(String[] args) {
String s = "A B C D E F G\tH I\rJ\nK\tL";
System.out.println("Current : "+s);
System.out.println("Single Space : "+singleSpace(s));
System.out.println("Space count : "+spaceCount(s));
System.out.format("Replace all = %s", s.replaceAll("\\s+", ""));
// Example where it uses the most.
String s = "My name is yashwanth . M";
String s2 = "My nameis yashwanth.M";
System.out.println("Normal : "+s.equals(s2));
System.out.println("Replace : "+s.replaceAll("\\s+", "").equals(s2.replaceAll("\\s+", "")));
}
If String contains only single-space then replace() will not-replace,
If spaces are more than one, Then replace() action performs and removes spacess.
public static String singleSpace(String str){
return str.replaceAll(" +| +|\t|\r|\n","");
}
To count the number of spaces in a String.
public static String spaceCount(String str){
int i = 0;
while(str.indexOf(" ") > -1){
//str = str.replaceFirst(" ", ""+(i++));
str = str.replaceFirst(Pattern.quote(" "), ""+(i++));
}
return str;
}
Pattern.quote("?") returns literal pattern String.
My method before I found the second answer using regex as a better solution. Maybe someone needs this code.
private String replaceMultipleSpacesFromString(String s){
if(s.length() == 0 ) return "";
int timesSpace = 0;
String res = "";
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(c == ' '){
timesSpace++;
if(timesSpace < 2)
res += c;
}else{
res += c;
timesSpace = 0;
}
}
return res.trim();
}
Stream version, filters spaces and tabs.
Stream.of(str.split("[ \\t]")).filter(s -> s.length() > 0).collect(Collectors.joining(" "))
I know replaceAll method is much easier but I wanted to post this as well.
public static String removeExtraSpace(String input) {
input= input.trim();
ArrayList <String> x= new ArrayList<>(Arrays.asList(input.split("")));
for(int i=0; i<x.size()-1;i++) {
if(x.get(i).equals(" ") && x.get(i+1).equals(" ")) {
x.remove(i);
i--;
}
}
String word="";
for(String each: x)
word+=each;
return word;
}
String myText = " Hello World ";
myText = myText.trim().replace(/ +(?= )/g,'');
// Output: "Hello World"
string.replaceAll("\s+", " ");
If you already use Guava (v. 19+) in your project you may want to use this:
CharMatcher.whitespace().trimAndCollapseFrom(input, ' ');
or, if you need to remove exactly SPACE symbol ( or U+0020, see more whitespaces) use:
CharMatcher.anyOf(" ").trimAndCollapseFrom(input, ' ');
public class RemoveExtraSpacesEfficient {
public static void main(String[] args) {
String s = "my name is mr space ";
char[] charArray = s.toCharArray();
char prev = s.charAt(0);
for (int i = 0; i < charArray.length; i++) {
char cur = charArray[i];
if (cur == ' ' && prev == ' ') {
} else {
System.out.print(cur);
}
prev = cur;
}
}
}
The above solution is the algorithm with the complexity of O(n) without using any java function.
Please use below code
package com.myjava.string;
import java.util.StringTokenizer;
public class MyStrRemoveMultSpaces {
public static void main(String a[]){
String str = "String With Multiple Spaces";
StringTokenizer st = new StringTokenizer(str, " ");
StringBuffer sb = new StringBuffer();
while(st.hasMoreElements()){
sb.append(st.nextElement()).append(" ");
}
System.out.println(sb.toString().trim());
}
}

how to process string in java

I want to make strings like "a b c" to "prefix_a prefix_b prefix_c"
how to do that in java?
You can use the String method: replaceAll(String regex,String replacement)
String s = "a xyz c";
s = s.replaceAll("(\\w+)", "prefix_$1");
System.out.println(s);
You may need to tweek the regexp to meet your exact requirements.
Assuming a split character of a space (" "), the String can be split using the split method, then each new String can have the prefix_ appended, then concatenated back to a String:
String[] tokens = "a b c".split(" ");
String result = "";
for (String token : tokens) {
result += ("prefix_" + token + " ");
}
System.out.println(result);
Output:
prefix_a prefix_b prefix_c
Using a StringBuilder would improve performance if necessary:
String[] tokens = "a b c".split(" ");
StringBuilder result = new StringBuilder();
for (String token : tokens) {
result.append("prefix_");
result.append(token);
result.append(" ");
}
result.deleteCharAt(result.length() - 1);
System.out.println(result.toString());
The only catch with the first sample is that there will be an extraneous space at the end of the last token.
hope I'm not mis-reading the question. Are you just looking for straight up concatenation?
String someString = "a";
String yourPrefix = "prefix_"; // or whatever
String result = yourPrefix + someString;
System.out.println(result);
would show you
prefix_a
You can use StringTokenizer to enumerate over your string, with a "space" delimiter, and in your loop you can add your prefix onto the current element in your enumeration. Bottom line: See StringTokenizer in the javadocs.
You could also do it with regex and a word boundary ("\b"), but this seems brittle.
Another possibility is using String.split to convert your string into an array of strings, and then loop over your array of "a", "b", and "c" and prefix your array elements with the prefix of your choice.
You can split a string using regular expressions and put it back together with a loop over the resulting array:
public class Test {
public static void main (String args[]) {
String s = "a b c";
String[] s2 = s.split("\\s+");
String s3 = "";
if (s2.length > 0)
s3 = "pattern_" + s2[0];
for (int i = 1; i < s2.length; i++) {
s3 = s3 + " pattern_" + s2[i];
}
System.out.println (s3);
}
}
This is C# but should easily translate to Java (but it's not a very smart solution).
String input = "a b c";
String output (" " + input).Replace(" ", "prefix_")
UPDATE
The first solution has no spaces in the output. This solution requires a place holder symbol (#) not occuring in the input.
String output = ("#" + input.Replace(" ", " #")).Replace("#", "prefix_");
It's probably more efficient to use a StringBuilder.
String input = "a b c";
String[] items = input.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
StringBuilder sb = new StringBuilder();
foreach (String item in items)
{
sb.Append("prefix_");
sb.Append(item);
sb.Append(" ");
}
sb.Length--;
String output = sb.ToString();

Categories

Resources