正则表达式从字符串中获取特定值

时间:2017-07-16 06:00:37

标签: java regex

字符串输出低于结果。

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 

我的目的是将值test179901034102 , test179901083723 e tc作为与字符串分开的列表。

如何使用正则表达式从下面的字符串中获取值(`test179901034102,test179901083723)

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

3 个答案:

答案 0 :(得分:1)

您可以使用^[^ ]+

示例:

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));
}

请参阅:{{3}}

答案 1 :(得分:0)

XPath 1.0不支持正则表达式。 XPath 2.0有一些支持正则表达式的函数:matches(), replace(), tokenize()

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

答案 2 :(得分:0)

请尝试使用此核心java代码并根据您的平台进行修改

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));
  }

 }
}

使用https://www.freeformatter.com/java-regex-tester.html#ad-output试用正则表达式