Psl
Psl

Reputation: 3920

regex to get particular values from a string

A string outputs below result.

test179901034102 00:00:00:00:00:01 Open
test179901083723 00:00:00:00:00:01 Open
test179901153595 00:00:00:00:00:01 Open
test179901187836 00:00:00:00:00:01 Open

 WebElement element = driver.findElement(By.xpath("//div[contains(@class,'filteredTable')]"));
 System.out.println( element.getText()); // returns the above string 

My intention is to get the values test179901034102 , test179901083723 etc as a list separately from the string.

How can i use regex to get the values(`test179901034102 , test179901083723) from the below string

test179901034102 00:00:00:00:00:01 Open
test179901083723 00:00:00:00:00:01 Open
test179901153595 00:00:00:00:00:01 Open
test179901187836 00:00:00:00:00:01 Open

Upvotes: 0

Views: 243

Answers (3)

Jared Rummler
Jared Rummler

Reputation: 38121

You can use ^[^ ]+.

Example:

String s = "test179901034102 00:00:00:00:00:01 Open\n" +
    "test179901083723 00:00:00:00:00:01 Open\n" +
    "test179901153595 00:00:00:00:00:01 Open\n" +
    "test179901187836 00:00:00:00:00:01 Open";

Pattern pattern = Pattern.compile("^[^ ]+", Pattern.MULTILINE);
Matcher matcher = pattern.matcher(s);
while (matcher.find()) {
  System.out.println(matcher.group(0));
}

See: https://regex101.com/r/aZYgvC/1

Upvotes: 1

Vikas
Vikas

Reputation: 7165

XPath 1.0 does not support regular expressions. XPath 2.0 has some functions which support regular expressions: matches(), replace(), tokenize()

driver.findElement(By.xpath("//div[matches(text(),'test\d+')"));

Upvotes: 0

PotatoManager
PotatoManager

Reputation: 1775

Please try this core java code and modify according to your platform

import java.util.regex.*;
public class HelloWorld{

 public static void main(String []args){
   String input="test179901034102 00:00:00:00:00:01 Open\n test179901083723 00:00:00:00:00:01 Open\n test179901153595 00:00:00:00:00:01 Open\n test179901187836 00:00:00:00:00:01 Open";

  Pattern pattern=Pattern.compile("test[0-9]*");
  Matcher m = pattern.matcher(input);

  while (m.find()) {
    System.out.println(m.group(0));
  }

  Pattern pattern2=Pattern.compile("([0-9]{2}:){5}[0-9]{2}");
  Matcher m2 = pattern2.matcher(input);

  while (m2.find()) {
   System.out.println(m2.group(0));
  }

 }
}

Use https://www.freeformatter.com/java-regex-tester.html#ad-output to try out regexes

Upvotes: 0

Related Questions