I am going to use the following method to replace special BB Codes for html links
public String replace(String text , String bbcode , String imageLocation ){
StringBuffer imageBuffer = new StringBuffer ("");
Pattern pattern = Pattern.compile("\\"+bbcode );
Matcher matcher = pattern.matcher(text);
StringBuilder builder = new StringBuilder();
int i = 0;
while (matcher.find()) {
//String orginal = replacements.get(matcher.group(1));
imageBuffer.append("<img src=\"" + imageLocation + "\" />");
String replacement = imageBuffer.toString();
builder.append(text.substring(i, matcher.start()));
if (replacement == null) {
builder.append(matcher.group(0));
} else {
builder.append(replacement);
}
i = matcher.end();
}
builder.append(text.substring(i, text.length()));
return builder.toString();
}
but when it comes to replacing the following bbcodes ,
:D
O:-)
:-[
:o)
:~(
:xx(
:-]
:-(
^3^
#_#
:O
:)
:P
;-)
???
?_?
Z_Z
It turns out to be not closing bracket and : <-- not recognized
How should I override the regex functional code and replace the abovementioned list of icons as html image links?
I am currently using this string array but
It comes out with the following error
error: Error: No resource type specified (at '^index_6' with value '#_#').
<string-array name="hkgicon_array">
<item>[369]</item>
<item>#adore#</item>
<item>#yup#</item>
<item>#ass#</item>
<item>:-(</item>
<item>^3^</item>
<item>#_#</item>
</string-array>
USE QUOTE
You can use Pattern pattern = Pattern.compile(Pattern.quote(bbcode ));
in your code instead of Pattern.compile("\\"+bbcode );.
Try this code:
public static String replace(String text , String bbcode , String imageLocation ){
StringBuffer imageBuffer = new StringBuffer ("");
Pattern pattern = Pattern.compile(Pattern.quote(bbcode ));
Matcher matcher = pattern.matcher(text);
StringBuilder builder = new StringBuilder();
int i = 0;
while (matcher.find()) {
//String orginal = replacements.get(matcher.group(1));
imageBuffer.append("<img src=\"" + imageLocation + "\" />");
String replacement = imageBuffer.toString();
builder.append(text.substring(i, matcher.start()));
if (replacement == null) {
builder.append(matcher.group(0));
} else {
builder.append(replacement);
}
i = matcher.end();
}
builder.append(text.substring(i, text.length()));
return builder.toString();
}
Refer stackoverflow for more details .
Related
I have to display string with visible control characters like \n, \t etc.
I have tried quotations like here, also I have tried to do something like
Pattern pattern = Pattern.compile("\\p{Cntrl}");
Matcher matcher = pattern.matcher(str);
String controlChar = matcher.group();
String replace = "\\" + controlChar;
result = result.replace(controlChar, replace);
but I have failed
Alternative: Use visible characters instead of escape sequences.
To make control characters "visible", use the characters from the Unicode Control Pictures Block, i.e. map \u0000-\u001F to \u2400-\u241F, and \u007F to \u2421.
Note that this requires output to be Unicode, e.g. UTF-8, not a single-byte code page like ISO-8859-1.
private static String showControlChars(String input) {
StringBuffer buf = new StringBuffer();
Matcher m = Pattern.compile("[\u0000-\u001F\u007F]").matcher(input);
while (m.find()) {
char c = m.group().charAt(0);
m.appendReplacement(buf, Character.toString(c == '\u007F' ? '\u2421' : (char) (c + 0x2400)));
if (c == '\n') // Let's preserve newlines
buf.append(System.lineSeparator());
}
return m.appendTail(buf).toString();
}
Output using method above as input text:
␉private static String showControlChars(String input) {␍␊
␉␉StringBuffer buf = new StringBuffer();␍␊
␉␉Matcher m = Pattern.compile("[\u0000-\u001F\u007F]").matcher(input);␍␊
␉␉while (m.find()) {␍␊
␉␉␉char c = m.group().charAt(0);␍␊
␉␉␉m.appendReplacement(buf, Character.toString(c == '\u007F' ? '\u2421' : (char) (c + 0x2400)));␍␊
␉␉␉if (c == '\n')␍␊
␉␉␉␉buf.append(System.lineSeparator());␍␊
␉␉}␍␊
␉␉return m.appendTail(buf).toString();␍␊
␉}␍␊
Simply replace occurences of '\n' with the escaped version (i.e. '\\n'), like this:
final String result = str.replace("\n", "\\n");
For example:
public static void main(final String args[]) {
final String str = "line1\nline2";
System.out.println(str);
final String result = str.replace("\n", "\\n");
System.out.println(result);
}
Will yield the output:
line1
newline
line1\nnewline
just doing
result = result.replace("\\", "\\\\");
will work!!
Here's my problem:
I need to remove a semicolon in a String but this String comes from a semicolon separated file in excel.
I need to replace a semicolon only if there's a quotation mark after the word.
ie:
data1;data2;"This is a duck;";data3;"Here's another duck";
needs to be replaced by:
data1;data2;"This is a duck";data3;"Here's another duck";
What is the best way to do this ?
Edit: Here's what i tried:
String line = myLine;
line.replaceAll(("\\w*;"),$1);
but i can't make it work and I dont think that its the best way to do it. I also tried
line = line.replaceall(";\"", "\"");
But that doesn't work because it replace
data1;data2;"This is a duck;";data3;"Here's another duck";
for
data1;data2"This is a duck";data3"Here's another duck";
If only you want regex :
public static void main (String[] args) throws java.lang.Exception
{
Pattern p = Pattern.compile ( "\"(.*);\"");
String input1 = "\"This is duck;\"";
String input2 = "This is duck;";
Matcher m = p.matcher(input1);
if ( m.find() )
{
input1 = m.group(1);
System.out.println( "Modified input1 is : " + input1 );
}
else
{
System.out.println( "input1 is not modified" );
}
m = p.matcher(input2);
if ( m.find() )
{
input2 = m.group(1);
System.out.println( "Modified input2 is : " + input2 );
}
else
{
System.out.println( "input2 is not modified" );
}
}
Output :
Modified input1 is : This is duck
input2 is not modified
Probably not the best but easiest way:
String str = "\"This is a duck;\"";
str = str.replace(";\"", "\"")
You should not use regex for that. You should use a csv parser and writer.
For example, here's how you can do it with OpenCSV:
CSVReader reader = new CSVReader(new FileReader("myCsv.csv"),';');
CSVWriter writer = new CSVWriter(new FileWriter("corrected.csv"), ';');
String[] lineTokens;
while ((lineTokens = reader.readNext()) != null) {
for(String token : lineTokens) {
token.replace(";", "");
}
writer.writeNext(lineTokens);
}
writer.close();
If you need to do an operation on a csv, use the right tool. Help yourself and use a csv parser.
Use regex with positive lookahead assertion
/;(?=")/g
Example :
String pattern = ";(?=\")";
String updated = STRING.replaceAll(pattern, "");
or
String pattern = ";\"";
String updated = STRING.replaceAll(pattern, "\"");
I have a string which contains normal text and Unicode in between, for example "abc\ue415abc".
I want to replace all occurrences of \\u with \u. How can I achieve this?
I used the following code but it's not working properly.
String s = "aaa\\u2022bbb\\u2014ccc";
StringBuffer buf = new StringBuffer();
Matcher m = Pattern.compile("\\\\u([0-9A-Fa-f]{4})").matcher(s);
while (m.find()) {
try {
int cp = Integer.parseInt(m.group(1), 16);
m.appendReplacement(buf, "");
buf.appendCodePoint(cp);
} catch (NumberFormatException e) {
}
}
m.appendTail(buf);
s = buf.toString();
Please help. Thanks in advance.
From API reference: http://developer.android.com/reference/java/lang/String.html#replace(java.lang.CharSequence, java.lang.CharSequence)
You can use public
public String replace (CharSequence target, CharSequence replacement)
string = string.replace("\\u", "\u");
or
String replacedString = string.replace("\\u", "\u");
Your initial string doesn't, in fact, have any double backslashes.
String s = "aaa\\u2022bbb\\u2014ccc";
yields a string that contains aaa\u2022bbb\u2014ccc, as \\ is just java string-literal escaping for \.
If you want unicode characters: (StackOverflow21028089.java)
import java.util.regex.*;
class StackOverflow21028089 {
public static void main(String[] args) {
String s = "aaa\\u2022bbb\\u2014ccc";
StringBuffer buf = new StringBuffer();
Matcher m = Pattern.compile("\\\\u([0-9A-Fa-f]{4})").matcher(s);
while (m.find()) {
try {
// see example:
// http://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#appendReplacement%28java.lang.StringBuffer,%20java.lang.String%29
int cp = Integer.parseInt(m.group(1), 16);
char[] chars = Character.toChars(cp);
String rep = new String(chars);
System.err.printf("Found %d which means '%s'\n", cp, rep);
m.appendReplacement(buf, rep);
} catch (NumberFormatException e) {
System.err.println("Confused: " + e);
}
}
m.appendTail(buf);
s = buf.toString();
System.out.println(s);
}
}
=>
Found 8226 which means '•'
Found 8212 which means '—'
aaa•bbb—ccc
If you want aaa\u2022bbb\u2014ccc, that's what you started with. If you meant to start with a string literal with aaa\\u2022bbb\\u2014ccc, that's this:
String s = "aaa\\\\u2022bbb\\\\u2014ccc";
and converting it to the one with single slashes can be as simple as #Overv's code:
s = s.replaceAll("\\\\u", "\\u");
though since backslash has a special meaning in regex patterns and replacements (see Matcher's docs) (in addition to java parsing), this should probably be:
s = s.replaceAll("\\\\\\\\u", "\\\\u");
=>
aaa\u2022bbb\u2014ccc
Try this:
s = s.replace(s.indexOf("\\u"), "\u");
There is a contains method and a replace method in String. That being said
String hello = "hgjgu\udfgyud\\ushddsjn\hsdfds\\ubjn";
if(hello.contains("\\u"))
hello.replace("\\u","\u");
System.out.println(hello);
It will print :- hgjgu\udfgyud\ushddsjn\hsdfds\ubjn
I want to replace text "1\n2" ("1" new line and "2")with for example "abcd". I've been searching a lot for solution but I can't find.
Below is my code
String REGEX = "1\n2";
Pattern p = Pattern.compile(REGEX, Pattern.DOTALL);
Matcher m = p.matcher(text);
String newText = m.replaceAll("abcd");
[EDIT]
I'd like to add that text variable is read from file:
String text = new Scanner(new File("...")).useDelimiter("\\A").next();
Try to change your regex to
String REGEX = "1\\n2";
So it escapes the \n
Example:
public static void main(String[] args) {
String REGEX = "1\n2";
Pattern p = Pattern.compile(REGEX, Pattern.DOTALL);
Matcher m = p.matcher("test1\n2test");
String newText = m.replaceAll("abcd");
System.out.println(newText);
}
O/P:
testabcdtest
Or even simply
String newText = "test1\n2test".replaceAll("1\n2", "abcd");
O/P
testabcdtest
Why use a regex for this? Just use
String newText = text.replace("1\n2", "abcd");
try this
String str="Your String"
str=str.replace("1\n2","abc");
How would I transform a text like the following or any other text containing an URL (http ftp etc)
Go to this link http://www.google.com (ofc stack overflow already does this, on my website this is just plain text);
Into this
Go to this link www.google.com
I've come up with this method
public String transformURLIntoLinks(String text){
String urlValidationRegex = "(https?|ftp)://(www\\d?|[a-zA-Z0-9]+)?.[a-zA-Z0-9-]+(\\:|.)([a-zA-Z0-9.]+|(\\d+)?)([/?:].*)?";
Pattern p = Pattern.compile(urlValidationRegex);
Matcher m = p.matcher(text);
StringBuffer sb = new StringBuffer();
while(m.find()){
String found =m.group(1); //this String is only made of the http or ftp (just the first part of the link)
m.appendReplacement(sb, ""http"
}
m.appendTail(sb);
return sb.toString();
}
The problem is the regexes i've tried match only the first part("http" or "ftp").
My output becomes: Go to this link <a href='http'>http</a>
It should be this
Go to this link <a href='http://www.google.com'>http://www.google.com</a>
public String transformURLIntoLinks(String text){
String urlValidationRegex = "(https?|ftp)://(www\\d?|[a-zA-Z0-9]+)?.[a-zA-Z0-9-]+(\\:|.)([a-zA-Z0-9.]+|(\\d+)?)([/?:].*)?";
Pattern p = Pattern.compile(urlValidationRegex);
Matcher m = p.matcher(text);
StringBuffer sb = new StringBuffer();
while(m.find()){
String found =m.group(0);
m.appendReplacement(sb, "<a href='"+found+"'>"+found+"</a>");
}
m.appendTail(sb);
return sb.toString();
}
m.group(1) was the mistake. m.group(0) works.
This will transform any URL found in the text into an anchor.