为什么在上次打开括号后不拆分字符串?

时间:2018-12-13 17:46:39

标签: r regex stringr

我正在尝试用最后一次出现的左括号(“(”)括号来分割字符串,但是由于某些原因,R和stringr::str_split无法识别出该字符串。

理想情况下,我希望字符串分割(PP)

有什么想法吗?

library(stringr)

## Doesn't Work
str_split("Ben Meyers (1), Hank Crone (1) (PP)", "\\([^\\(]*$", simplify = TRUE)
#>      [,1]                              [,2]
#> [1,] "Ben Meyers (1), Hank Crone (1) " ""

## Works
str_split("Ben Meyers (1), Hank Crone (1) (PP)", "\\(", simplify = TRUE)
#>      [,1]          [,2]              [,3]  [,4] 
#> [1,] "Ben Meyers " "1), Hank Crone " "1) " "PP)"

reprex package(v0.2.0)于2018-12-13创建。

1 个答案:

答案 0 :(得分:3)

您可以使用

public static void main(String ar[]) {
        System.setProperty("webdriver.chrome.driver","D:\\Study\\selenium-java-2.48.2\\selenium-2.48.2\\chromedriver.exe");
        driver=new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.manage().window().maximize();
        driver.get("https://www.westernunion.com/global-service/track-transfer");
        driver.findElement(By.xpath("//input[@id='trackingNumber']")).sendKeys("2587051083");
        driver.findElement(By.xpath("//button[@id='button-track-transfer']")).click();
        }

模式为"\\((?=[^(]*$)"

  • \((?=[^(]*$)-一个\(
  • (-正向超前查询,需要除(?=[^(]*$)之外的0个或多个字符,直到当前位置右侧的字符串末尾为止。

R测试:

(

如果您要在最后一个右括号之前从元素“修剪”空白,则可以在开头添加> library(stringr) > str_split("Ben Meyers (1), Hank Crone (1) (PP)", "\\((?=[^(]*$)", simplify = TRUE) [,1] [,2] [1,] "Ben Meyers (1), Hank Crone (1) " "PP)" (以匹配0个或更多空白):

\s*

请参见regex demo online