Hi to parse String "x;y:z" in Core Java
hi to parse String "x;y:z" in Core Java
Deepak_A_L wrote:
how do i parse a String "X;Y:Z" in java i.e the results of parsing the string
String s = "X;Y:Z"
in terms of ENGLISH LANGUAGE -->(X Semicolon Y Colon Z)
should be the below o/p individual Strings.
X
Y
Z
how do i get the above output.????Split on a semi- or regular colon using String's split(String regex) method.
Similar Messages
-
i have problem to parse string to document
i have string like this str = "<root><data>1</data><data>2</data><root>";
how to parse this string in docoment xmlimport java.io.*;
import org.jdom.*;
import org.jdom.input.*;
import org.jdom.output.*;
public class PrettyPrinter {
public static void main(String[] args) {
// Assume filename argument
String filename = args[0];
try {
// Build the document with SAX and Xerces, no validation
SAXBuilder builder = new SAXBuilder();
// Create the document
Document doc = builder.build(new File(filename));
// Output the document, use standard formatter
XMLOutputter fmt = new XMLOutputter();
fmt.output(doc, System.out);
} catch (Exception e) {
e.printStackTrace();
}The above code is taken directly from
http://www.javaworld.com/javaworld/jw-05-2000/jw-0518-jdom-p2.html
u don't have to use Factories, this is what is said in that excerpt, it is very easy to use, and it is said that 80 % of the xml work can be done with 20 % or less work using JDOM.
n joy ....
</ksenji> -
How to parse string to date in j2me?
How to parse string to date in j2me?
Please help me.Hi..
String dyStr = "20";
String mtStr = "1";
String yrStr = "1999";
Calendar cal = Calendar.getIntstance();
int dy = Integer.parseInt(dyStr);
int mt = Integer.parseInt(mtStr);
int yr = Integer.parseInt(yrStr);
cal.set(Calendar.DATE, dy);
cal.set(Calendar.MONTH, mt);
cal.set(Calendar.YEAR, yr);
OK? -
How could i parse string and link its model with my files in eclipse project?
How could i parse string and link its model with my files in eclipse project?, as i read that we dont have to use standalone mode while working with eclipse projects.
Example of what i want to do:
I have file1.dsl in my project which contains some statements but the declaration of these statements are not in another file, i need to put them only in my codeHi Stefan,
I have eclipse project contains 2 files, file1.dsl and file2.dsl, you can see the contents of the files below.
file1.dsl contains some statements as shown below and file2.dsl contains the declarations of the variables. (like in C++ or Java we have declarations and usage)
At this step file1.dsl and file2.dsl will be parsed successfully without any errors.
Lets imagine that we will delete this project and will create another one and the new project will contain only file1.dsl (which contains the usage)
At this step this file (file1.dsl) will contains some errors after parsing it, because we are using variables without declarations.
So what i need is to parse the content of file2.dsl directly without adding this file to the project.
I need to add the content of file2.dsl directly as a string in the code and parse it. just like that ( "int a;int b;" )
And link file1.dsl with the model generated after parsing my string
file1.dsl
a++;
b++;
file2.dsl
int a;
int b;
Thanks -
I need to parse strings in the format "City State
Abbreviation Zipcode" (ie "Glenview, IL 60062") to seperate them as
their own variables. Problem is that sometimes there is a comma
after city, sometimes not, so I've resorted to REfind to seperate
the string. Here's the snippet, "city" is the entire string I
mentioned above. The problem is that the refind I use seems to be
returning 0. I'm trying to find the two capital letters that
designate the state abbeviation.
<cfif city neq ''>
<cfset crpos = refind("[:upper:][:upper:]",city) >
<cfset zip = trim(right(city,len(city)-crpos))>
<cfset citystate = trim(left(city,crpos)) >
<cfset newpos = find("#chr(32)#",citystate) >
<cfset state =
trim(right(citystate,len(citystate)-newpos)) >
<cfset actualcity =
trim(left(citystate,len(citystate)-newPos)) >
</cfif>I probably should mention some explaination about what the
regular expression is doing:
Note: Groups are RegExp statements surrounded by ()
Group 1: Combination of Letters and Spaces (e.g. City Name)
optional comma and (required) space
Group 2: 2 Character upper case state code (State Code) (note
- depending on your source, state codes may not always be upper
case)
(required) space
Group 3: 5 digit string (e.g. Zip Code) (note - again,
depending on your source, you may be getting 5 digit zip + 4 or
even non-us zip codes that may involve alpha characters.)
The replace function is using back references to refer to the
text matched by group 1,2 and 3. -
Split Function unable to parse string correctly
Hi,
I'm using split function to split string into multiple rows using comma "," as delimiter. In a string I have following values which are not parsed correctly as they have comma inside the values.
American Dawn, Inc.
Battalian USA, Inc.
Fria USA, Inc.
Lazer, Inc.
Mexilink Inc.
Is there any other approach to fix this issue?
Here is the split function Im using:
CREATE Function [dbo].[fnSplit] (
@List varchar(MAX),
@Delimiter char(1)
Returns @Temp1 Table (
ItemId int Identity(1, 1) NOT NULL PRIMARY KEY ,
Item varchar(MAX) NULL
As
Begin
Declare @item varchar(MAX),
@iPos int
Set @Delimiter = ISNULL(@Delimiter, ';' )
Set @List = RTrim(LTrim(@List))
-- check for final delimiter
If Right( @List, 1 ) <> @Delimiter -- append final
delimiter
Select @List = @List + @Delimiter -- get position of
first element
Select @iPos = Charindex( @Delimiter, @List, 1 )
While @iPos > 0
Begin
-- get item
Select @item = LTrim( RTrim( Substring( @List, 1, @iPos
-1 ) ) )
If @@ERROR <> 0 Break -- remove item form list
Select @List = Substring( @List, @iPos + 1, Len(@List)
- @iPos + 1 )
If @@ERROR <> 0 Break -- insert item
Insert @Temp1 Values( @item ) If @@ERROR <> 0 Break
-- get position pf next item
Select @iPos = Charindex( @Delimiter, @List, 1 )
If @@ERROR <> 0 Break
End
Return
End
Another user in this forum posted a split function that
he wrote:
CREATE FUNCTION dbo.splitter(@string VARCHAR(MAX), @delim CHAR(1))
RETURNS @result TABLE (id INT IDENTITY, value VARCHAR(MAX))
AS
BEGIN
WHILE CHARINDEX(@delim,@string) > 0
BEGIN
INSERT INTO @result (value) VALUES (LEFT(@string,CHARINDEX(@delim,@string)-1))
SET @string = RIGHT(@string,LEN(@string)-CHARINDEX(@delim,@string))
END
INSERT INTO @result (value) VALUES (@string)
RETURN
END
GO
Both of them are unable to parse above values incorrectly.
FYI: String is made of values that are selected
by user in SSRS report. I think SSRS when combine values , put comma "," between multiple values.
Any help or guidance would be appreciated.
ZKduplicate of
https://social.msdn.microsoft.com/Forums/sqlserver/en-US/820ac53c-ce25-4cc7-b828-5875a21d459d/split-function-unable-to-parse-string-correctly-in-ssrs-report?forum=sqlreportingservices
please dont cross post
Please Mark This As Answer if it solved your issue
Please Vote This As Helpful if it helps to solve your issue
Visakh
My Wiki User Page
My MSDN Page
My Personal Blog
My Facebook Page -
I'm trying to make a small prog that extracts a song's artist from its filename based on a specified pattern.
Something like this:
public String getArtist(String filename, string pattern) {
String artist = getArtist("The artist - the title.mp3", "artist - title");
artist = getArtist("01 - Another title - Another artist.mp3", "track - title - artist");Any good ideas on how to implement getArtist would be appreciated... :)heres my idea of how to solve it...
this solution is not complete, but you may perfect it any way you like... it's just a quick and dirty hack ;)
import java.util.regex.*;
public class ArtistProblem {
public static void main(String[] args) {
if (args.length == 2) {
System.out.println(getArtist(args[0], args[1]));
} else {
System.out.println(getArtist("The artist - the title.mp3", "artist - title"));
System.out.println(getArtist("01 - Another title - Another artist.mp3", "track - title - artist"));
public static String getArtist(String filename, String pattern) {
// change track to regex that matces any spaces nad word characters
pattern = pattern.replaceAll("track", "[\\\\w ]*");
// change title to regex that matces any spaces nad word characters
pattern = pattern.replaceAll("title", "[\\\\w ]*");
// remove extention from the end of filename
filename = filename.replaceAll("\\.mp3$", "");
// change artist to regex that groups matched pattern
pattern = pattern.replaceAll("artist", "([\\\\w ]*)");
Pattern patt = Pattern.compile(pattern);
Matcher matcher = patt.matcher(filename);
if (matcher.find()) {
return matcher.group(1);
} else {
// no match was found, so we return empty string
return "";
}try running it so:
java ArtistProblem "the artist - the track - the title.mp3" "artist - track - title"
and you'll get:
the artist
i hope that gives you a jumpstart to some direction. -
How do i search for a string in a txt file using java??
How do i search for a string in a txt file using java??
could you please help thanks
JRegular expressinos work just fine, especially when
searching for patterns. But they seem to be impying
it's a specific group of characters they're looking
for, and indexOf() is much faster than a regex.If he's reading from a file, the I/O time will likely swamp any performance hit that regex introduces. I think contains() (or indexOf() if he's not on 5.0 yet) is preferable to regex just because it's simpler. (And in the case of contains(), the name makes for a very clear, direct mapping between your intent and the code that realizes it.) -
Revision: 18053
Revision: 18053
Author: [email protected]
Date: 2010-10-07 03:27:37 -0700 (Thu, 07 Oct 2010)
Log Message:
BLZ-571: Use of wrong operator in string comparison in flex.messaging.VersionInfo.java
Updated the code to use the right operator.
Check-in Tests: PASS
QA: Yes
Ticket Links:
http://bugs.adobe.com/jira/browse/BLZ-571
Modified Paths:
blazeds/trunk/modules/core/src/flex/messaging/VersionInfo.java -
This is my function to convert a string into a desired output format.But my Date in the desired output format is coming out to be null.Could smeone plz point out my mistake.
Date getDateInDesiredFormat(String strInputDate,String strInputFormat,String strOutputFormat)
try
SimpleDateFormat sdfInput = new SimpleDateFormat(strInputFormat);
SimpleDateFormat sdfOutput = new SimpleDateFormat("MM-dd-yyyy");
ParsePosition pos = new ParsePosition(0);
Date dtInputDate=sdfInput.parse(strInputDate.trim(),pos);
System.out.println(dtInputDate);
String strFormattedDate=sdfOutput.format(dtInputDate);
System.out.println(strFormattedDate);
Date dtOutputDate=sdfOutput.parse(strFormattedDate.trim(),pos);
if(dtOutputDate==null)
System.out.println("dtOutputDate is null ");
else
System.out.println(dtOutputDate.toString());
return dtOutputDate;
catch (NullPointerException npex)
return null;
catch(Exception ex)
return null;
}This is how i am calling the function
Date date=getDateInDesiredFormat("Fri Sep 30 20:30:56 IST 2006","EE MMM d HH:mm:ss ZZZ yyyy","MM-dd-yyyy");
}You need to use the sdfInput object to parse the date and sdfOutput to format and print it (like you did before your 'if'):
SimpleDateFormat sdfInput = new SimpleDateFormat(strInputFormat);
SimpleDateFormat sdfOutput = new SimpleDateFormat("MM-dd-yyyy");
Date dtInputDate=sdfInput.parse(strInputDate.trim());
String strFormattedDate=sdfOutput.format(dtInputDate);
System.out.println(strFormattedDate);the toString() you use in the else block uses a default format, not the one you specify. -
Parse String in OBIEE Answers.
Please can someone help me to know how to parse a string in obiee answers:
Eg: 'Administrators;XMLP_ADMIN;319'.
I can do this very easy in Java but not sure how to do it in OBIEE. Appreciate your help
Regards.Hi,
what are you expecting to do with that string? can you be more specific?
you want to have all values before the semi colon?
you can use regexp in obiee to parse these kind of strings..
i think this must be helpful to you..
http://oraclebizint.wordpress.com/2009/06/04/oracle-bi-ee-10-1-3-4-1-handling-complex-string-manipulations-using-regular-expressions-regex-and-evaluate/
if its helpful award points
thanks,
karthick
Edited by: kart on May 28, 2010 3:56 PM -
Hello,
What is the proper way to parse XML String instead of a XML file?.Use new InputSource(new StringReader(s)).
Good luck. -
Parsing String to XML Attribute bug
Hello!
I'm trying to convert String to org.w3c.dom.Document with javax.xml.parsers.DocumentBuilder, but when I check my XML Document after creating, I find that all the Attributes are like "" or "
 ". Does anyone have some idea why that problem is and how it can be solved?
Thanks a lot!
SvigiThere are lots of bug reports about Java 5's built-in XML parser screwing up on attribute values. Try forcing Java to use the current version of Xerces (download it) instead of whatever it has built in, if that seems to apply to you. On the other hand it's possible that the bug is in your code too.
-
I didn't find a method that parses a XML document when it's not a file. I have a String that I want to parse and the method DocumentBuilder.parse only accepts a String that is a uri to a file.
I write this code:
String strXML = "<?xml version='1.0' ?><root><node>anything</node></root>";
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
domDoc = docBuilder.parse(strXML);
Please gimme a light!!
[]'s
SauloI have a similar problem, I'm trying to do the same BUT in a servlet, it compiles and it actually works if I use it outside my servlet, but, when I mount the servlet with the code similar to this one here it doesn't read the string (at least that's what appears to be, because it doesn't writes to my DB as it should and it doesn't display anything as I'm specifying as my servlet response). Any help? I'm posting my code here:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.w3c.dom.*;
import org.apache.xml.serialize.*;
import java.net.URLDecoder;
import java.sql.*;
import org.xml.sax.InputSource;
import java.io.StringReader;
public class SMSConnector extends HttpServlet
//Public variables we will need
public String Stringid;
public String Stringpath;
public String st;
public int nid;
//Servlet service method, which permits listening of events
public void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
//Initialization for the servlet
ServletOutputStream salida = res.getOutputStream();
ServletInputStream entrada = req.getInputStream();
//Reading of the entering string
BufferedReader lector = new BufferedReader(new InputStreamReader (entrada));
res.setContentType("text/HTML");
try {
//Database handler
Class.forName("org.gjt.mm.mysql.Driver");
//DocumentBuilderFactory factory =
//DocumentBuilderFactory.newInstance();
//DocumentBuilder builder = factory.newDocumentBuilder();
InputSource inStream = new InputSource();
inStream.setCharacterStream(new StringReader(lector.readLine()));
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc1 = docBuilder.parse(inStream);
NodeList listasms = doc1.getElementsByTagName("sms");
for(int s=0; s<listasms.getLength() ; s++)
Connection Conn = DriverManager.getConnection ("jdbc:mysql://localhost:3306/smsdb","root", "");
Node nodosms = listasms.item(s);
if(nodosms.getNodeType() == Node.ELEMENT_NODE){
Element elementosms = (Element)nodosms;
NodeList listatelf = elementosms.getElementsByTagName("tlf");
Element elementotelf = (Element)listatelf.item(0);
NodeList textTelfList = elementotelf.getChildNodes();
String telefono = ((Node)textTelfList.item(0)).getNodeValue();
//String SendingAddress = ((Node)textAddressList.item(0)).getNodeValue().trim();
salida.println(telefono);
NodeList listaop = elementosms.getElementsByTagName("op");
Element elementoop = (Element)listaop.item(0);
NodeList textOpList = elementoop.getChildNodes();
String operadora = ((Node)textOpList.item(0)).getNodeValue();
NodeList listasc = elementosms.getElementsByTagName("sc");
Element elementosc = (Element)listasc.item(0);
NodeList textSCList = elementosc.getChildNodes();
String shortcode = ((Node)textSCList.item(0)).getNodeValue();
NodeList listabody = elementosms.getElementsByTagName("body");
Element elementobody = (Element)listabody.item(0);
NodeList textBodyList = elementobody.getChildNodes();
String body = ((Node)textBodyList.item(0)).getNodeValue();
Statement sta = Conn.createStatement();
sta.executeUpdate("INSERT INTO smstable (telf,op,sc,body) VALUES ('" + telefono + "','" + operadora + "','" + shortcode + "','" + body + "')");
Conn.commit();
Conn.close(); }
//Catching errors for the SAX and XML parsing
catch (SAXParseException err)
System.out.println ("** Parsing error" + ", line " + err.getLineNumber () + ", uri " + err.getSystemId ());
System.out.println(" " + err.getMessage ());
catch (SAXException e)
Exception x = e.getException ();
((x == null) ? e : x).printStackTrace ();
catch (Throwable t)
t.printStackTrace ();
} -
DateFormat.parse(String)
can anybody tell me why I don't get a SHORT format:
import java.util.*;
import java.text.*;
public class MyDate{
public static void main(String[] args){
Date date = makeDate("04/22/2003");
System.out.println(date); // what i get looks more like FULL
public static Date makeDate(String dateString){
Date date = null;
try {
DateFormat fmt = DateFormat.getDateInstance(DateFormat.SHORT);
date = fmt.parse(dateString);
catch(ParseException e) {}
return date;
}Thank you.what I think is tripping you up is that a java.util.Date is not a String. It looks like you're thinking that you can format a java.util.Date object and somehow it is "11/23/2004" (or whatever) - but it's not - it's just a number. So, you have this String that you want to convert to a java.util.Date (which you correctly did with the parse method of the DateFormat class) but then you turn around and want to convert that java.util.Date to a String so you can put it into a List, so why not just put the original String into your List? Is it because you want to change the format? Fair enough, then you can use two DateFormat implementations, one to parse the incoming String to a Date, then the other to format the Date to the format you want. Or is it so you can do the sort chronologically? If that's the case, then you can write up a Comparator to do that, or you can store Dates in your list, sort them, and when it comes time to display this thing (if you ever do that) use a DateFormat implementation to convert those to a formatted String.
Make sense?
Maybe you are looking for
-
How to pass runtime process a commmand with pipes?
I have this java program to run commands, but it ignore any command with pipes (e.g., ps -ef | grep -v grep | grep defunct). Any ideas on how to do this? It tries to pass every after -ef into ps as part of a ps command instead of directing output dow
-
I compiled a custom madwifi module using a patch for the Atheros 5007EG chipset. If I upgrade the kernel, will it break the module? Will I have to recompile everytime I get a kernel? I currently have the kernel ignored by pacman.
-
Trackpad issues - Windows 7 64-bit
Hi. This may have been posted already, but I can't seem to find any topics. I just installed Windows 7 64-bit on my Macbook, 2.4 Intel Core 2 Duo, and am unable to right click when in Boot Camp. I'm running OSX 10.6.6. Should I just install the 32-bi
-
Fill free space with specific playlist
Hi Guys, Had a search but couldn't see the answer. How do I fill the free space on my iPhone with songs from a specific playlist on iTunes then force iTunes to re-randomize on each sync? Thanks! Max
-
ABAP Object Generator/converter
Has anyone come across a function module or class-method that will create, define and build a ABAP Object Class? Inbound interface would need to include the basics of the Class definition (e.g., class name, supertype, methods, functions to convert to