簡體   English   中英

使用正則表達式在字符串中查找模式->如何改善我的解決方案

[英]Find pattern in string with regex -> how to improve my solution

我想解析一個字符串並獲取"stringIAmLookingFor" -部分,該字符串在結尾和開頭均被"\\_"包圍。 我正在使用正則表達式來匹配它,然后在找到的字符串中刪除"\\_" 這是可行的,但我想知道是否有更優雅的方法來解決此問題?

String test = "xyz_stringIAmLookingFor_zxy";
Pattern p = Pattern.compile("_(\\w)*_");
Matcher m = p.matcher(test);
while (m.find()) { // find next match
    String match = m.group();
    match = match.replaceAll("_", "");
    System.out.println(match);
}

解決方案(部分)

請同時檢查下一部分。 不要只在這里閱讀解決方案。

只需稍微修改一下代碼:

String test = "xyz_stringIAmLookingFor_zxy";

// Make the capturing group capture the text in between (\w*)
// A capturing group is enclosed in (pattern), denoting the part of the
// pattern whose text you want to get separately from the main match.
// Note that there is also non-capturing group (?:pattern), whose text
// you don't need to capture.
Pattern p = Pattern.compile("_(\\w*)_");

Matcher m = p.matcher(test);
while (m.find()) { // find next match

    // The text is in the capturing group numbered 1
    // The numbering is by counting the number of opening
    // parentheses that makes up a capturing group, until
    // the group that you are interested in.
    String match = m.group(1);
    System.out.println(match);
}

Matcher.group() ,不帶任何參數,將返回整個正則表達式模式匹配的文本。 Matcher.group(int group)將返回通過捕獲具有指定組號的組匹配的文本。

如果您使用的是Java 7,則可以使用命名捕獲組 ,這會使代碼更具可讀性。 可以使用Matcher.group(String name)訪問由捕獲組匹配的Matcher.group(String name)

String test = "xyz_stringIAmLookingFor_zxy";

// (?<name>pattern) is similar to (pattern), just that you attach 
// a name to it
// specialText is not a really good name, please use a more meaningful
// name in your actual code
Pattern p = Pattern.compile("_(?<specialText>\\w*)_");

Matcher m = p.matcher(test);
while (m.find()) { // find next match

    // Access the text captured by the named capturing group
    // using Matcher.group(String name)
    String match = m.group("specialText");
    System.out.println(match);
}

模式問題

注意\\w也匹配_ 您所擁有的模式是模棱兩可的,並且我不知道在字符串中包含多於2 _的情況下您的預期輸出是什么。 並且是否要允許下划線_成為輸出的一部分?

使用group(1)而不是group()因為group()將為您提供整個模式,而不是匹配的組。

參考: http : //docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#group(int)

您可以定義所需的組,因為您已經在使用括號。 您只需要稍微調整一下模式即可。

String test = "xyz_stringIAmLookingFor_zxy";
Pattern p = Pattern.compile("_(\\w*)_");
Matcher m = p.matcher(test);
while (m.find()) { // find next match
    System.out.println(m.group(1));
}
"xyz_stringIAmLookingFor_zxy".replaceAll("_(\\w)*_", "$1");

將用括號將此組替換所有內容

一個更簡單的正則表達式,不需要組:

"(?<=_)[^_]*"

如果您想要更嚴格:

"(?<=_)[^_]+(?=_)"

嘗試

    String s = "xyz_stringIAmLookingFor_zxy".replaceAll(".*_(\\w*)_.*", "$1");
    System.out.println(s);

輸出

stringIAmLookingFor

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM