Help: String.replaceAll(regex,string) !!!
i want to replace a string(called str) such as
"Don't hesitate to cantact us "
into
"Don\'t hesitate to cantact us "
what statment i should take ??
i am in a Jsp page, with
<%= str.replaceAll("'", "\'") %> or
<%= str.replaceAll("'", "\\'") %> or
<%= str.replaceAll("'", "\\\'") %>
i got always wrong or unchanged string ...
Help !!!!!!!!!!!!!!!!!!!!!!!!!
well if your tomcat uses jdk1.4 or above you can import java.util.Regx.* and use replaceAll() method on string in your jsp page, otherwise write your own code to substring the two string & add "\" at the end of the first string then join the two substrings.
Similar Messages
-
Hi i was wondering if anyone could hep me create a regex pattern.
I need to search a String for the substring "X-Mozilla-Status: ****" where the four stars can be any number,
i came up with this:
"X-Mozilla-Status: [0-9]+"but the program isn't working and im asuming its because this isn't right.
can anyone help?
thankslol ok,
the output is exactly the same as the input text, nothing has been replaced (and yes there are plenty of the subtrings lurking in the text file to be replaced).
no exceptions are being thrown.
current code:
import java.io.*;
public class EmailFixer {
public static void main(String[] args) {
String line = "";//string to hold each line as it is read in
String text = "";//string to hold entire text file, each line is added
String regex = "^X-Mozilla-Status: [0-9]+$";//regex pattern to replace
String replace = "X-Mozilla-Status: 0005";//replacement string
try{
*read inbox.txt line by line, adding to text String
BufferedReader in = new BufferedReader(new FileReader("inbox.txt"));
while ((line = in.readLine()) != null){
text = text + "\n" + line;
*once all text is read in replace all text which matched regex pattern with replacement String
text = text.replaceAll(regex, replace);
in.close();
System.out.println(text);//print out the ammended text
catch(Exception e){//catch exceptions
e.printStackTrace();
}//end main
}//end classinput (and coincidentally output):
Test file
From - Wed Sep 24 00:06:17 2008
X-Account-Key: account3
X-UIDL: 1
X-Mozilla-Status: 0009
X-Mozilla-Status2: 10000000
X-Mozilla-Keys:
Return-Path: <[email protected]>
From - Wed Sep 24 00:06:17 2008
X-Account-Key: account3
X-UIDL: 1
X-Mozilla-Status: 0002
X-Mozilla-Status2: 10000000
X-Mozilla-Keys:
Return-Path: <[email protected]>
From - Wed Sep 24 00:06:17 2008
X-Account-Key: account3
X-UIDL: 1
X-Mozilla-Status: 0003
X-Mozilla-Status2: 10000000
X-Mozilla-Keys:
Return-Path: <[email protected]>
From - Wed Sep 24 00:06:17 2008
X-Account-Key: account3
X-UIDL: 1
X-Mozilla-Status: 0001
X-Mozilla-Status2: 10000000
X-Mozilla-Keys:
Return-Path: <[email protected]> -
Using a local variable in regex portion of replaceAll(regex, replacement)
While this works..
output = output.replaceAll("(HED>|AUT>)(.*)(</\\1)", "$1<![CDATA[$2]]>$3");
I'd like the list of alternation values to be contained in a variable, for example:
String nodeLIst = "HED>|AUT>";
output = output.replaceAll("(nodeList)(.*)(</\\1)", "$1<![CDATA[$2]]>$3");
The extension of this would be so I can store this stuff in a db as a list and avoid compilation on change, but please don't let this muddy the waters... :)
Any pointers are much appreciated. Links to specific reading material, etc. I've scoured Friedl's Mastering Regular Expressions to no avail. This approach is supported by some other regex engines I've used (perl, php, ORO?) but I'm new to Java.
TIA,
MarkI've scoured Friedl's Mastering Regular Expressions to no avail.Did you look on page 209? In the book, that code sample is labelled "Building Up a Regex Through Variables in Java". That should have been a clue. ^_^
But seriously, you're probably thinking of the interpolated strings you find in scripting languages like Perl, PHP, Ruby, etc.. But that's a feature of the language itself, not the regex engine, and Java doesn't work that way. (The $1, $2, etc., in the replacement string are processed by the Matcher class, in a very limited imitation of Perl's variable interpolation).
However, you can fake it pretty well with String's format() method: String regex = String.format("(%s)(.*)(</\\1)", theAlternation);
output = output.replaceAll(regex, "$1<![CDATA[$2]]>$3"); That way, you can easily escape the dynamic part, in case it might contain regex metacharacters: String regex = String.format("(%s)(.*)(</\\1)", Pattern.quote(theAlternation)); -
Help needed with regex package
Hi,
I need help about using regex package in the following way.
a String/CharSequence should be there which will be given to the Pattern.compile(REGEX) method.
I need the REGEX sequences according to the strings below
1) From: "*" <*@*> :: Here * is for any number of charecters
2) we will have some file names I want only those files which end with .txt format.
Please help me in writing the regular expressions for the above criteria.String regex = "From: *[^<]+<[^@]+@[^>]+>";would you need to escape out *'s? forgot if you need to escape quantifiers
and for the file you would want something like
"(.*)\.txt"check out
http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html -
String.replaceAll(regex, with what);
im looking for a way to replace specific instances of words in a string
for instance, replace %URL% with a specific URL in a string. the problem is i cant get replace all to recognize %URL% without using something like \\p{symbol} or something like that with %URL%
i've tried
"%URL%"
"\%URL\%"
but none work
help please :)
thanksString str = "this address %URL% is fake";
String addr = "http://some.name.com";
String result = str.replaceAll("%URL%",
addr);produces
this address http://some.name.com is fake
So the % is not a special character...
to OP: If it isn't working, read the error more closely. Post it here if you still have problems. -
Hi guys,
I want to edit a string by using a function like UpperCase or LowerCase. Is there any function in ABAP which has the same functionality?
next problem is:
Can i use this function in an SQL query?
Like: Select SINGLE IDSEGMENT
FROM Table
INTO IDSEG
WHERE Upcase(string1) = Upcase(string2).
Is this possible?
Problem is that in the DB the string1 is spelled different (capital letters) than string2Hi,
Try this out
*Code to demonstrate TRANSLATE to UPPER/LOWER CASE command
DATA: ld_char(20) type c.
ld_char = 'Hello World'.
TRANSLATE ld_char TO UPPER CASE. "Result: ld_char = 'HELLO WORLD'
TRANSLATE ld_char TO LOWER CASE. "Result: ld_char = 'hello world'
See this link
http://help.sap.com/saphelp_46c/helpdata/en/fc/eb33a5358411d1829f0000e829fbfe/frameset.htm
Thanks & Regards,
Judith. -
HELP: String to double conversion?
Hello,
I want to convert a String to a double, and then use this double for a calculation. The conversion seems to be ok, but I get an error with the calculation... Please HELP!
A part of my code:
double angle;
Double converted_angle;
angle=jTextField2.getText();
converted_angle= Double.valueOf(angle);
double theta = cos(Math.PI/180*converted_angle);
ERROR: "operator * cannot be applied to double,java.lang.Double"
Thanks in advance.This is happening because you want to multiply a Double object, instead of a double value. Do this:
Double converted_angle; should be double converted_angle;
converted_angle= Double.valueOf(angle); should be changed to converted_angle = Double.parseDouble(angle);
angle should probably be a String.
check this link for your options:
http://java.sun.com/j2se/1.4/docs/api/java/lang/Double.html -
hi how can I convert this into String ?
please change this code into String
please help me
Thank you for helping me
public class Sort {
public void bubble_srt( char a[], int n ){
int i, j;
char t;
for(i = 0; i < n; i++){
for(j = 1; j < (n-i); j++){
if(a[j-1] > a[j]){
t = a[j-1];
a[j-1]=a[j];
a[j]=t;
}}Edited by: Showbee on Mar 10, 2008 3:37 AMString s = "public class Sort {"+
" public void bubble_srt( char a[], int n ){"+
" int i, j;"+
" char t;"+
" for(i = 0; i < n; i++){"+
" for(j = 1; j < (n-i); j++){"+
" if(a[j-1] > a[j]){"+
" t = a[j-1];"+
" a[j-1]=a[j];"+
" a[j]=t;"+
" }"+
" }"+
" }"+
" }}"; -
Need help: String to XML
Hi everyone,
Im looking for some assistance regarding string to xml. I wanted to extract the xml from the field 'sendDataReturn'. Is my xsl script correct?
XML in String
<sendDataResponse xmlns="http://service.aes.cust.mic.at" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<sendDataReturn><b><?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?> <MicExportResponseMessage xmlns="http://www.mic-cust.com/Webservice/MicExportWS/v1.1"><Connection><connectionID>MICWEBSERVICE</connectionID><partnerID>SAPKLD400</partnerID><dateTime>2008-12-12T09:35:40</dateTime></Connection><Messages><Message><Envelope><messageID>1</messageID><partyID>01</partyID><schemaID>V 1.0 B01</schemaID><sequenceNum>1</sequenceNum><transActionID>970002570-01-TR-V3</transActionID></Envelope><Detail><actionCode><code>ER</code></actionCode><error><errorSource>MIC</errorSource><errorCode>106615</errorCode><errorType>ERR</errorType><errorText>Objekt ist schon in der Datenbank vorhanden</errorText></error></Detail></Message></Messages></MicExportResponseMessage></b></sendDataReturn>
</sendDataResponse>
XSL SCRIPT
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ns0="http://service.aes.cust.mic.at">
<xsl:template match="/">
<xsl:for-each select="//sendDataReturn">
<xsl:value-of select="." disable-output-escaping="yes"/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
ThanksHi
In order to apply an xsl your input needs to be valid xml. In your example this starts at the XML declaration
<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?>
<MicExportResponseMessage xmlns="http://www.mic-cust.com/Webservice/MicExportWS/v1.1">
<Connection>
<connectionID>MICWEBSERVICE</connectionID>
<partnerID>SAPKLD400</partnerID>
<dateTime>2008-12-12T09:35:40</dateTime>
</Connection>
<Messages>
<Message>
<Envelope>
<messageID>1</messageID>
<partyID>01</partyID>
<schemaID>V 1.0 B01</schemaID>
<sequenceNum>1</sequenceNum>
<transActionID>970002570-01-TR-V3</transActionID>
</Envelope>
<Detail>
<actionCode>
<code>ER</code>
</actionCode>
<error>
<errorSource>MIC</errorSource>
<errorCode>106615</errorCode>
<errorType>ERR</errorType>
<errorText>Objekt ist schon in der Datenbank vorhanden</errorText>
</error>
</Detail>
</Message>
</Messages>
</MicExportResponseMessage>
To Output all the inpit xml see here use the xsl:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ns0="http://service.aes.cust.mic.at">
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
It looks like you are trying to extract the xml from a syschronous call response, the xsl above may bot be the entire solution but a atarting point at least to extract data, tags included .. you can eaisly test this in a xsl tool such as xml spy (there is a trial version) .. -
Help:String arg[ ] problems
Hi:
I am having problems with my encryption program and I want to check that the contents at the command line a being read properly.
ex: java Monoalphabet -k feather in.txt out.txt
-k(indicates encryption)
feather(keyword)
How do I check to make sure that the input in being read into String args[]properly?
Thanks.Print the args out using System.out.println() in a loop at the beginning of your main method.
-
Help- String representation of an object
I have a question- if i made many objects like this
server=new Server(name, location);
and i wanted to see the result in full
could i just do
for(int i=0; i<numServer; i++)
System.out.println(server[i]);
when i do this i get some nonsense coming out
Server@1c5c1
but i want to see the WHOLE server object with the name and locationOverride toString .
-
Is there a way to make a regex which matches one of two particular words?
I've designed a method which acts as a prompt for user input. It accepts 3 parameters, all Strings: the first a description of the prompt (e.g. "Enter Date:"), the second a regex expression, and the last an error message in case the user's input doesn't match the regex expression. The prompt method prints the string, compares the user's input to the regex, and either returns the input, or prints the error message and repeats itself.
One of the methods calling this prompt method requires the user's input to be one of two words, "business" or "personal". Therefore the method needs to specify a regex for these words and these words only. Can this be done?
Sorry if this is a little confusing, I'm only just now learning regexs. Thanks to anyone who can help.This one works fine. Any way to make it ignore the capitalization of each letter, though? Right now it only works if the input is in lower case...
-
Help with a regex finction:
I'm trying to do this but not matter what clientNameFilter.text contains I always get false returned
var pattern:RegExp = new RegExp('/.*' + clientNameFilter.text + '.*/');
var test :int = (item.clientName as String).search(pattern) ;
if (
(item.clientName as String).search(pattern) == -1
return false;
Any ideas?If this post answers your question or helps, please mark it as such.
Greg Lafrance - Flex 2 and 3 ACE certified
www.ChikaraDev.com
Flex / AIR Development, Training, and Support Services
Don't need / in regex in this case:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
private function checkEntry():void {
var pattern:RegExp;
if(clientNameFilter.text){
pattern = new RegExp('.*' + clientNameFilter.text + '.*');
if (txt.text.search(pattern)!=-1){
mx.controls.Alert.show("true");
}else{
mx.controls.Alert.show("false");
]]>
</mx:Script>
<mx:HBox>
<mx:Label text="Your input:"/>
<mx:TextInput id="txt"/>
</mx:HBox>
<mx:HBox>
<mx:Label text="Filter string:"/>
<mx:TextInput id="clientNameFilter"/>
</mx:HBox>
<mx:Button label="Check" click="checkEntry()"/>
</mx:Application> -
Help needed about regex usage.
hi all,
i am kind of new to java.util.regex, and i can't solve this problem:
i have a big string, that actually represents the text code of a method. in this method, i have an object, called, let's say "visitor" and i call several non static methods of it. i need to search this string and put into an ArrayList<String> all the occurrences of visitor, the method called, and its parameters.
if i wasn't very clear, here is an example:
the input string: "public void test_add()
TemplateTestMethodVisitor visitor = new TemplateTestMethodVisitor(XMLArrayListTest.class);
XMLArrayListComparer comparer = new XMLArrayListComparer();
while(visitor.moveNext())
fillArrayList(visitor);
Exception exception = null;
try
_testedArray.add(visitor.getParameterAsInt("position"), ValueFactory.getMemberValue(visitor,
visitor.getParameterAsString("type"), "ElementValue"));
catch(Exception e)
exception = e;
ExceptionValidator.validateException(visitor, exception);
if(exception != null)
continue;
VisitorAssert.assertEquals(visitor, "The content of the array list is not as expected.",
visitor.getResultAsCollectionData("List"), _testedArray, comparer);
and i need to obtain an ArrayList<String> with {"visitor.moveNext()", "visitor.getParameterAsInt("position")" , "visitor.getParameterAsString("type")", "visitor.getResultAsCollectionData("List")"}. and it would be very helpful for me to do this using regex, but i can't think of a right pattern...
thank you all.import java.io.*;
import java.util.regex.*;
public class TestRegexp {
public static void main(String[] argv) {
Pattern p = Pattern.compile("visitor\\..*?\\(.*?\\)");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
while((line = in.readLine()) != null) {
Matcher m = p.matcher(line);
while(m.find()) {
System.out.println(m.group());
} catch(IOException e) {
e.printStackTrace();
} -
Help with some regex wildcard searching
Please could someone help
I am just wanting to use ? to match with any one character
and to match star with any number of character
*(ta followed by star could be multiple words (talk, table etc)*
*(?a? could be multiple words (cat, bat etc)*
The array of strings are working and are in sorted order
fred only shows one entry and not frederica*
public void pattern()
System.out.println("Pattern Matching");
boolean b;
for (int i=0; i < arrayNumber i++)
b = Pattern.matches("fred*", searchTheWords);
if (b)
System.out.println(searchTheWords[i]);The pattern:
fred*will match:
fre
fred
fredd
freddd
freddddI think you want
fred.*
Maybe you are looking for
-
I was able to change my apple id on my ipad, but am unable to change it on my iphone 4
I created a new apple id in my computer. but the id was changed on my ipad only. the apple id on my iphone 4 did not change. how can i change it?
-
So frustrated to see my servlet cant connect to mysql database, anyone pls help me? i put mysql-connector-java-2.0.14-bin.jar in C:\Apache\Tomcat 4.0\common\lib C:\Apache\Tomcat 4.0\webapps\ROOT\WEB-INF\lib D:\j2sdk1.4.0_03\jre\lib\ext here the excep
-
Alrighty, I'm using Photoshop CS4 Extended, and I'm having troubles with motion blur. When I set the angle to anything above 60 really and distance to about 300 it crashes saying Adobe Photoshop CS4 has encountered a problem and needs to close. This
-
When i use the video chat in facebook, the video of the other party is not able to display
any body experience thesame thing
-
Faces images in Photos Library
It seems that iPhone has taken the zoomed and cropped photo that's used for Faces and imported it in to my Photo library. Also, I have a ton of duplicates all of the sudden. I went from 4,000 photos to over 9,000. Old photos that were previously dele