Parsing a string in powershell
I've looked around a bit and can't quite find an answer to this. I've got a script going that looks at a configuration file, and I need to find the values that is inside of quotes.
config file:
Version = "3.2"
currently in my script I simply have
$Versionvalue = get-content $ConfigFile | select-string "Version"
However this returns the whole string and I need just the number that is in quotes, in Unix I would do this with some cut commands, but I haven't quite found the equivalent in my searches.
Thanks in advance
You need to use parenthesis to do capturing. You can do numbered captures, or named captures. This looks like a fairly simple regular expression, so numbered is fine.
Here are two examples using both numbered and named captures with Select-String. This assumes your version is always 'Major.Minor'. If you have revision or build numbers in there (even if they're optional), you'll need to modify the regex. (I don't use select-string
very much, so there might be a better way to do this):
# Numbered
Get-Item $ConfigFile | Select-String -pattern 'Version = "(\d+\.\d+)"' | select -exp matches | % { $_.groups[1].Value }
# Named
Get-Item $ConfigFile | Select-String -pattern 'Version = "(?<version>\d+\.\d+)"' | select -exp matches | % { $_.groups["version"].Value }
Here's how I would do it using the -match comparison operator (which doesn't mean it's the best way). For more info on the -match operator, see the about_Comparison_Operators help topic:
# Numbered:
Get-Content $ConfigFile | foreach { if ($_ -match 'Version = "(\d+\.\d+)"') { $matches[1] } }
# Named:
Get-Content $ConfigFile | foreach { if ($_ -match 'Version = "(?<version>\d+\.\d+)"') { $matches.version } }
Note that if your config file has more than one 'Version = "x.x"' line in it, you'll get more than one result back.
Similar Messages
-
Parsing a string using StringTokenizer
Hi,
I want to parse a string such as
String input = ab{cd}:"abc""de"{
and the extracted tokens should be as follows
ab
cd
"abc""de"
As a result, I used the StringTokenizer class with deilmeter {,},:
StringTokenizer tokenizer = new StringTokenizer(input,"{}:", true);
In this was, I can separate the tokens and also can get the delimeters. The problem is I don't know how to parse the string that has double quote on it. If a single quote " is taken as a delimeter then
", abc, ",", de," all of them will be taken as a separate token. My intention is to get the whole string inside the double quote as a token including the quotes on it. Moreover, if there is any escape character "", it should be also included in the token. Help please.
ThanksA bit of a "sticky tape"-solution...
import java.util.StringTokenizer;
public class Test {
public static void main(String[] args) {
String input = "ab{cd}:\"abc\"\"de\"";
StringTokenizer st = new StringTokenizer(input, "{}:", true);
while(st.hasMoreTokens()) {
String token = st.nextToken();
if(token.startsWith("\"") && token.endsWith("\"")) {
token = token.substring(1,token.length()-1);
System.out.println(token);
} -
How to Parse a string into an XML DOM ?
Hi,
I want to parse a String into an XML DOM. Not able to locate any parser which supports that. Any pointers to this?Download Xerces from xml.apache.org. Place the relevant JAR's on your classpath. Here is sample code to get a DOM document reference.
- Saish
public final class DomParser extends Object {
// Class Variables //
private static final DocumentBuilder builder;
private static final String JAXP_SCHEMA_LANGUAGE =
"http://java.sun.com/xml/jaxp/properties/schemaLanguage";
/** W3C schema definitions */
private static final String W3C_XML_SCHEMA =
"http://www.w3.org/2001/XMLSchema";
// Constructors //
static {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(true);
factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
builder = factory.newDocumentBuilder();
builder.setErrorHandler(new ErrorHandler() {
public void warning(SAXParseException e) throws SAXException {
System.err.println("[warning] "+e.getMessage());
public void error(SAXParseException e) throws SAXException {
System.err.println("[error] "+e.getMessage());
public void fatalError(SAXParseException e) throws SAXException {
System.err.println("[fatal error] "+e.getMessage());
throw new XmlParsingError("Fatal validation error", e);
catch (ParserConfigurationException fatal) {
throw new ConfigurationError("Unable to create XML DOM document parser", fatal);
catch (FactoryConfigurationError fatal) {
throw new ConfigurationError("Unable to create XML DOM document factory", fatal);
private DomParser() {
super();
// Public Methods //
public static final Document newDocument() {
return builder.newDocument();
public static final Document parseDocument(final InputStream in) {
try {
return builder.parse(in);
catch (SAXException e) {
throw new XmlParsingError("SAX exception during parsing. Document is not well-formed or contains " +
"illegal characters", e);
catch (IOException e) {
throw new XmlParsingError("Encountered I/O exception during parsing", e);
}- Saish -
Parsing formatted String to Int
How can I parse formatted string to Integer ?
I have a formated string like this $900,000 and I need to convert it to 900000 so I could do calculations with it.
I tried something like this
NumberFormat nf = NumberFormat.getIntegerInstance(request.getLocale());
ttlMargin=nf.parse(screenVal);I got this exception
"java.lang.NumberFormatException: For input string: "$1,050,000""I am working on the JSP file that provides
margins,sales etc. I am reading this data off the
screen where it is beeing displayed according to the
accounting practices.
That's why I get it as a formatted string and why I
am trying covert that string to the numberScreen-scraping is a problematic, bad design. It sounds like what you really want is to call a web service which returns its results as data that a program can understand (XML, for example), not HTML (which is meant more for humans to read). I know, you probably can't change the design at this point... just food for thought. In the meantime, you'll probably have to manually parse those strings yourself by stripping out the '$' and ',' characters and then use parseInt on the result. -
How to parse a string containing xml data
Hi,
Is it possible to parse a string containing xml data into a array list?
my string contains xml data as <blood_group>
<choice id ='1' value='A +ve'/>
<choice id ='2' value='B +ve'/>
<choice id ='3' value='O +ve'/>
</blood_group>how can i get "value" into array list?There are lot of Java XML parsing API's available, e.g. JAXP, DOM4J, JXPath, etc.
Of course you can also write it yourself. Look which methods the String API offers you, e.g. substring and *indexOf. -
Passing / parsing XML String IN / OUT from PL / SQL package
Hello, People !
I am wondering where can I find exact info (with code sample) about following :
We use Oracle 8.1.6 and 8.1.7. I need to pass an XML String (could be from VARCHAR2 to CLOB) from VB 6.0 to PL/SQL package. Then I need to use built in PL/SQL XML parser to parse given string (could be large hierarchy of nodes)
and the return some kind of cursor thru I can loop and insert data into
different db Tables. (The return value may have complex parent/child data relationship - so I am not sure If this should be a cursor)
I looked online many site for related info - can't find what I am looking
for - seems like should be a common question.
Thanx a lot !Hello, People !
I am wondering where can I find exact info (with code sample) about following :
We use Oracle 8.1.6 and 8.1.7. I need to pass an XML String (could be from VARCHAR2 to CLOB) from VB 6.0 to PL/SQL package. Then I need to use built in PL/SQL XML parser to parse given string (could be large hierarchy of nodes)
and the return some kind of cursor thru I can loop and insert data into
different db Tables. (The return value may have complex parent/child data relationship - so I am not sure If this should be a cursor)
I looked online many site for related info - can't find what I am looking
for - seems like should be a common question.
Thanx a lot ! -
Hi,
I need to parse,in CVP 7.0(1), the BAAccountNumber variable passed by the ICM dialer. Is there a built-in java class or other function that would help me do this?
Our BAAccountNumber variable looks something like this: 321|XXX12345678|1901|M. In IP IVR I use the "Get ICM Data" object to read the BAAccountNumber variable from ICM and then I use the "token index" feature to parse the variable (picture below).
Alternately, IP IVR also has a Java class that allows me to do this; the class is "java.lang.String" and the method is "public int indexOf(String,int)"
Is there something equivalent in CVP 7.0(1)?
thanksThanks again for your help. This is what I ended up doing:
This configurable action element takes a string seperated by two "|" (123|123456789|12)
and returns 3 string variables.
you can add more output variables by adding to the Setting array below.
// These classes are used by custom configurable elements.
import com.audium.server.session.ActionElementData;
import com.audium.server.voiceElement.ActionElementBase;
import com.audium.server.voiceElement.ElementData;
import com.audium.server.voiceElement.ElementException;
import com.audium.server.voiceElement.ElementInterface;
import com.audium.server.voiceElement.Setting;
import com.audium.server.xml.ActionElementConfig;
public class SOMENAMEHERE extends ActionElementBase implements ElementInterface
* This method is run when the action is visited. From the ActionElementData
* object, the configuration can be obtained.
public void doAction(String name, ActionElementData actionData) throws ElementException
try {
// Get the configuration
ActionElementConfig config = actionData.getActionElementConfig();
//now retrieve each setting value using its 'real' name as defined in the getSettings method above
//each setting is returned as a String type, but can be converted.
String input = config.getSettingValue("input",actionData);
String resultType = config.getSettingValue("resultType",actionData);
String resultEntityID = config.getSettingValue("resultEntityID",actionData);
String resultMemberID = config.getSettingValue("resultMemberID",actionData);
String resultTFNType = config.getSettingValue("resultTFNType",actionData);
//get the substring
//String sub = input.substring(startPos,startPos+numChars);
String[] BAAcctresults = input.split("\\|");
//Now store the substring into either Element or Session data as requested
//and store it into the variable name requested by the Studio developer
if(resultType.equals("Element")){
actionData.setElementData(resultEntityID,BAAcctresults[0]);
actionData.setElementData(resultMemberID,BAAcctresults[1]);
actionData.setElementData(resultTFNType,BAAcctresults[2]);
} else {
actionData.setSessionData(resultEntityID,BAAcctresults[0]);
actionData.setSessionData(resultMemberID,BAAcctresults[1]);
actionData.setSessionData(resultTFNType,BAAcctresults[2]);
actionData.setElementData("status","success");
} catch (Exception e) {
//If anything goes wrong, create Element data 'status' with the value 'failure'
//and return an empty string into the variable requested by the caller
e.printStackTrace();
actionData.setElementData("status","failure");
public String getElementName()
return "MEDDOC PARSER";
public String getDisplayFolderName()
return "SSC Custom";
public String getDescription()
return "This class breaks down the BAAccountNumber";
public Setting[] getSettings() throws ElementException
//You must define the number of settings here
Setting[] settingArray = new Setting[5];
//each setting must specify: real name, display name, description,
//is it required?, can it only appear once?, does it allow substitution?,
//and the type of entry allowed
settingArray[0] = new Setting("input", "Original String",
"This is the string from which to grab a substring.",
true, // It is required
true, // It appears only once
true, // It allows substitution
Setting.STRING);
settingArray[1] = new Setting("resultType", "Result Type",
"Choose where to store result \n" +
"into Element or Session data",
true, // It is required
true, // It appears only once
false, // It does NOT allow substitution
new String[]{"Element","Session"});//pull-down menu
settingArray[1].setDefaultValue("Session");
settingArray[2] = new Setting("resultEntityID", "EntityID",
"Name of variable to hold the result.",
true, // It is required
true, // It appears only once
true, // It allows substitution
Setting.STRING);
settingArray[2].setDefaultValue("EntityID");
settingArray[3] = new Setting("resultMemberID", "MemberID",
"Name of variable to hold the result.",
true, // It is required
true, // It appears only once
true, // It allows substitution
Setting.STRING);
settingArray[3].setDefaultValue("MemberID");
settingArray[4] = new Setting("resultTFNType", "TFNType",
"Name of variable to hold the result.",
true, // It is required
true, // It appears only once
true, // It allows substitution
Setting.STRING);
settingArray[4].setDefaultValue("TFNType");
return settingArray;
public ElementData[] getElementData() throws ElementException
return null; -
Date contructor deprecation : Parsing a String to Date
Hi All,
In Java 1.5 the Date() constructor Date(String s) is deprecated. As per the API Documentation DateFormat.Parse() method is used.
The following code from Java 1.4 version has to be upgraded to Java 1.5.
Existing Code:
Date dDate = new Date(sDate);
Modified Code:
DateFormat df = DateFormat.getDateInstance();
Date dDate = df.parse(sDate);
Here the DateFormat accepts a default formatting style as "Feb 01, 2007" and parses the String.
If the String sDate belongs to any other formatting style such as "01 Feb, 2007" or "01 Feb, 07" the code piece throws unparsable date error.
Please give your thougts on this issue to parse the string of any format..
Thanks,
Rajesh.Hi All,
In Java 1.5 the Date() constructor Date(String s) is
deprecated. As per the API Documentation
DateFormat.Parse() method is used.
The following code from Java 1.4 version has to be
upgraded to Java 1.5.
Existing Code:
Date dDate = new Date(sDate);
Modified Code:
DateFormat df = DateFormat.getDateInstance();
Date dDate = df.parse(sDate);
Here the DateFormat accepts a default formatting
style as "Feb 01, 2007" and parses the String.
If the String sDate belongs to any other formatting
style such as "01 Feb, 2007" or "01 Feb, 07" the code
piece throws unparsable date error.
Please give your thougts on this issue to parse the
string of any format..You can't. What date is this: "08/04/24"? 8 April, 1924? 4 August, 2024?
>
Thanks,
Rajesh. -
I have a Java class that calls a stored proc and passes a stringbuffer object to it. The sproc should parse the string to retrieve the different ids that are concatenated in the stringbuffer and for each id retrieve a row from a table and in the end return a cursor containing the returned rows.Can anyone help me out with the parsing logic for a pipe delimited string.
TathagataThis might help you. If you want to handle the cursor in java, then convert the below into a function which returns the cursor.
SQL> CREATE TABLE EMP(ENAME VARCHAR2(100),ENO NUMBER(5),DEPT NUMBER(5))
2 /
Table created.
SQL> INSERT INTO EMP VALUES('SCOTT',1,2);
1 row created.
SQL> INSERT INTO EMP VALUES('TIGER',2,5);
1 row created.
SQL> INSERT INTO EMP VALUES('THOMAS',3,10);
1 row created.
SQL> INSERT INTO EMP VALUES('PETER',4,10);
1 row created.
SQL> INSERT INTO EMP VALUES('HARRY',7,10);
1 row created.
SQL> CREATE OR REPLACE PROCEDURE PARSE_STRING(STR VARCHAR2)
2 AS
3 TYPE EmpCurTyp IS REF CURSOR;
4 emp_cv EmpCurTyp;
5 STRING VARCHAR2(1000);
6 type emp_t is table of emp%rowtype;
7 emp_tab emp_t;
8 BEGIN
9 STRING := REPLACE(STR,'|',',');
10 OPEN emp_cv FOR 'SELECT ENAME,ENO,DEPT FROM EMP WHERE ENO IN('||string||')';
11 FETCH emp_cv BULK COLLECT INTO EMP_TAB;
12 CLOSE emp_cv;
13 FOR I IN 1..EMP_TAB.LAST
14 LOOP
15 DBMS_OUTPUT.PUT_LINE(EMP_TAB(I).ENAME);
16 END LOOP;
17 EXCEPTION
18 WHEN OTHERS THEN
19 DBMS_OUTPUT.PUT_LINE('ERROR OCCURED ' || SQLCODE ||' ' || SQLERRM);
20 END;
21 /
Procedure created.
SQL> set serveroutput on;
SQL> BEGIN
2 PARSE_STRING('1|2|3|4');
3 END;
4 /
SCOTT
TIGER
THOMAS
PETER
PL/SQL procedure successfully completed.
SQL>Regards,
Mohana -
Parsing a string in a given order
Hi All,
I want to parse a string and rank it in a given order.
Eg : i have a string as 'A | B | C | D'. I would like to parse this string and give a rank in order.
It should appear as below.
Parsed string order
D 1
C 2
B 3
A 4
Any help is greatly appreciated..A database version would help us providing you with a relevant solution.
Starting with 10g, you can do :
SQL> var my_str varchar2(30)
SQL> exec :my_str := 'A|B|C|D'
PL/SQL procedure successfully completed
SQL> select item
2 , row_number() over(order by item desc) as rank
3 from (
4 select regexp_substr(:my_str,'[^|]+',1,level) as item
5 from dual
6 connect by level <= length(regexp_replace(:my_str,'[^|]+')) + 1
7 );
ITEM RANK
D 1
C 2
B 3
A 4
In 11.2 :
SQL> select *
2 from xmltable(
3 'for $i in ora:tokenize($str,"\|") order by $i descending return $i'
4 passing 'A|B|C|D' as "str"
5 columns item varchar2(10) path '.'
6 , rank for ordinality
7 )
8 ;
ITEM RANK
D 1
C 2
B 3
A 4
Edited by: odie_63 on 11 janv. 2012 12:56 - added 11.2 -
Parsing a string in PL/SQL?
I am parsing a string in PL/SQL and at a certain point(Length 45) of the string I would like to add a carriage return (Chr(10)), then continue with the string at that point and then again if the string is greater than Length 45 add a carriage return.
I program in Powerbuilder and have figured it out, but I have a problem when trying to add a carriage return at a certain point in the string in PL/SQL. There is the REPLACE(), but that will replace everything, but I only want to add it at that certain point of the string. With the PB function I can add the carriage return at a certain point, see code:
Li_pos = PosA( Ps_data, '*')
DO WHILE Li_pos > 0
ll_length = Li_pos - ll_old_pos
IF ll_length > 45 THEN
ll_old_pos = Li_pos
Ps_data = ReplaceA( Ps_data, Li_Pos, 1, ls_carriage_rtn) **This function gives me the ability to add a carriage return at a certain point in the string. **
Li_pos = PosA( Ps_data, '*', Li_pos + 1 + ls_carriage_rtn)
ELSE
Li_pos = PosA( Ps_data, '*', Li_pos + 1)
END IF
LOOP
I have incorporated the same logic in PL/SQL but I am looking for something similar to the ReplaceA function in PB, that will replace at a certain point in a string. I use an '*' as a placeholder and measure the length. Below is the PL/SQL code:
t_pos NUMBER;
t_old_pos NUMBER;
t_length NUMBER;
BEGIN
t_old_pos := 0;
t_pos := INSTR(in_model_list, '*');
WHILE t_pos > 0 LOOP
t_length := t_pos - t_old_pos; -- This looks at current position minus the old position, measures the length
IF t_length > 45 THEN
t_old_pos := t_pos;
*** add that carriage return
t_pos := INSTR(in_model_list, '*', t_pos + 1 + Chr(10)); -- get the new position
NULL;
ELSE
t_pos := INSTR(in_model_list, '*', t_pos + 1);
END IF;
NULL;
END LOOP;
Here is the data, what it looks like: William 112,* 500-A,* 500-U,* 520,* 560-A,* 560-E,* 680-E,* 680-F,* 680-V*
Any help would be much appreciated.
Thank you,
William
Edited by: William on Feb 28, 2012 6:56 AMFrank Kulash wrote:
[example]I played with your example and came to this:SQL> WITH my_string AS
2 (SELECT '1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890'
3 AS mt
4 FROM DUAL)
5 , line_length AS
6 (SELECT 13 AS chars
7 FROM DUAL)
8 SELECT LISTAGG (REGEXP_SUBSTR (mt,'(.{'|| line_length.chars|| '})', 1, LEVEL),chr(10)) WITHIN GROUP (ORDER BY LEVEL)
9 ||chr(10)
10 ||substr(mt,-mod(LENGTH (mt),line_length.chars)) as wrapped_text
11 FROM my_string
12 CROSS JOIN line_length
13 CONNECT BY LEVEL < 1+LENGTH (mt) ;
WRAPPED_TEXT
1234567890123
4567890123456
7890123456789
0123456789012
3456789012345
6789012345678
9012345678901
2345678901234
5678901234567
8901234567890
1234567890123
WRAPPED_TEXT
4567890123456
7890
SQL>*[Edit]* annotated that this is 11g only...
Edited by: T.PD on 29.02.2012 21:17 -
Choping up a string in powershell
I have a variable called $office
$Office = (get-aduser -Identity $Name -Properties * |select physicalDeliveryOfficeName).physicalDeliveryOfficeName
It produces results like this
01A;514;295;632;428;485;442;277;800;175
Of course it could be shorter or longer depending on how many locations the user is in.
Each location code will ALWAYS be separated by a semicolon.
Is there a way to break that up and use each code between the semicolons as a string that I could then use a foreach statement?
Thanks
LishronI had just found this article
http://blogs.technet.com/b/heyscriptingguy/archive/2014/06/11/powertip-split-string-with-powershell.aspx
Like it was written for me but you beat me to the bunch.
Thanks so so much!
Lishron -
Hi,
I'm having a problem with parsing a string. Basically, I want to take a string for example: "TomWentToTheShop" and divide it into a coherent sentence (Tom went to the shop).
I've started the code by breaking the string into a char array, and if the character is a capital then store the index in the array and then do a substring.
But I don't think this is the best way to solve the problem, if anyone has any ideas it would be greatly appreciated.
thanks.
char[] charRequestTypeArray = string.toCharArray();
for (int i = 1; i < (charRequestTypeArray.length -1); i++) {
char c = charRequestTypeArray;
if (Character.isUpperCase(c)) {
Arrays.fill(storeCapitalIndex, i);
else{
Arrays.fill(storeNonCapitalIndex, i);String s = "TomWentToTheShop";
System.out.println(s.charAt(0) + s.substring(1).replaceAll("((?<!^)[A-Z])", " $1").toLowerCase());or even just System.out.println(s.charAt(0) + s.substring(1).replaceAll("([A-Z])", " $1").toLowerCase());Edited by: sabre150 on Nov 11, 2007 9:40 PM -
I'm trying to find an easy way to parse a string like this
String, brand,model, number;
String toParse=(Sony)(VZ-12324)(1);Is there a simple way of parsing the string to the "(" and ")" are omitted and brand=Sony;
model=VZ-12324);
number="1";
???String toParse = "(Sony)(VZ-12324)(1)";
String[] parts = toParse.split("[()]");
String brand = parts[1];
String model = parts[3];
int number = Integer.parseInt(parts[5]);
System.out.println(brand);
System.out.println(model);
System.out.println(number); -
Can somebody tell me the function used to parse a string and how it works? All I want to do is seperate the string 'AG-01' into another string 'AG-' and an int '01'. I have been through numerous resources and have found nothing at all on parsing functions.
This in one way:
String txt = "AG-01";
String first = txt.substring(0,3);
int second = Integer.parseInt(txt.substring(3,5));
%>
First string:<%=first%>
Second int :<%=second%>
Bye
Beck74
Maybe you are looking for
-
Timeouts while using LDAP and TNSNAMES for names resolving
I use an OID for Oracle Names resolving at the client-side. I tested some errorcases because there are no HA-features implemented for the OID. So i have an LDAP.ORA with the adress and the ports of the OID. My SQLNET.ORA has this content: NAMES.DEFAU
-
Front Row gives me a white screen when activated
Hello When I activate Front Row with my remote, the whole screen turns white. I can hear the sounds, and I can hear the interface working, but the screen is blank white. How can I fix this? ---------------------S
-
TS1424 Cannot Connect to iTunes
I have an error message "4002" when purchasing from iTunes? Can any one help me resolve this. It says I am not connected yet everything else is operating normally. I am purchasing music and it won't download. Hmmmm
-
why do we have to buy mountain lion when we bought lion? Others who didn't purchase lion don't have to pay for it to move to mountain lion.
-
The method queueConnection.close() shuts down the broker.
Hi All, I want to send and recieve messages in the same application. I'm using embedded broker, here's the brokerConfig.xml <beans> <broker> <connector> <serverTransport uri="vm://localhost" /> </connector> <pe