在字符串中找到不在圆括号“()”内的破折号“-”

时间:2019-05-14 22:49:18

标签: java regex

我正在尝试查找/确定字符串是否包含不包含在圆括号“()”中的字符“-”。

我尝试过正则表达式 [^\(]*-[^\)]*, 但它不起作用。

示例:

  1. 100 - 200 mg->应该匹配,因为圆括号中没有包含“-”。
  2. 100 (+/-) units->不匹配

5 个答案:

答案 0 :(得分:2)

您必须使用正则表达式吗?您可以尝试仅遍历字符串并跟踪范围,如下所示:

public boolean HasScopedDash(String str)
{
    int scope = 0;
    boolean foundInScope = false;
    for (int i = 0; i < str.length(); i++)
    {
        char c = str.charAt(i);
        if (c == '(')
            scope++;
        else if (c == '-')
            foundInScope = scope != 0;
        else if (c == ')' && scope > 0)
        {
            if (foundInScope)
                return true;
            scope--;
        }
    }
    return false;
}

编辑:如评论中所述,可能希望排除破折号在圆括号后但没有圆括号的情况。 (即“ abc(2-xyz”)),上面的代码对此进行了解释。

答案 1 :(得分:1)

Java支持量化原子组,这有效。
它的工作方式是使用成对的括号及其内容,
并且不回馈任何东西,直到找到破折号-
这是通过 atomic group 构造(?> )完成的。

^(?>(?>\(.*?\))|[^-])*?-

https://www.regexplanet.com/share/index.html?share=yyyyd8n1dar
(单击Java按钮,检查 find() 函数列)

可读

 ^ 
 (?>
      (?> \( .*? \) )
   |  
      [^-] 
 )*?
 -

答案 2 :(得分:1)

Sub temp2()
Dim FoundCell As Range, LastCell As Range, DelRange As Range, FirstAddr As String
Set LastCell = Range("H" & Rows.Count)
Set FoundCell = Range("H:H").Find(what:="dnp", after:=LastCell)
Set DelRange = FoundCell
If Not FoundCell Is Nothing Then FirstAddr = FoundCell.Address
Do Until FoundCell Is Nothing
    Set FoundCell = Range("H:H").FindNext(after:=FoundCell)
    Set DelRange = Union(DelRange, FoundCell)
    If FoundCell.Address = FirstAddr Then Exit Do
Loop
If Not DelRange Is Nothing Then DelRange.EntireRow.Delete
End Sub

https://ideone.com/YXvuem

答案 3 :(得分:0)

您可能不想通过此检查。也许,您可以简单地检查其他界限。例如,此表达式检查破折号或您想要的中间任何其他字符前后的空格和数字,这很容易修改:

([0-9]\s+[-]\s+[0-9])

它将通过您的第一个输入,而使不需要的输入失败。您可以简单地使用逻辑OR将其他字符添加到其中间字符列表。

Demo

enter image description here

答案 4 :(得分:0)

如果您不介意使用2个正则表达式而不是1个复杂的正则表达式来检查字符串。您可以试试看

public static boolean match(String input) {
    Pattern p1 = Pattern.compile("\\-"); // match dash
    Pattern p2 = Pattern.compile("\\(.*\\-.*\\)"); // match dash within bracket

    Matcher m1 = p1.matcher(input);
    Matcher m2 = p2.matcher(input);

    if ( m1.find() && !m2.find() ) {
        return true;
    } else {
        return false;
    }
}

测试字符串

public static void main(String[] args) {
    String input1 = "100 - 200 mg";
    String input2 = "100 (+/-) units";
    System.out.println(input1 + " : " + ( match(input1) ? "match" : "not match") );
    System.out.println(input2 + " : " + ( match(input2) ? "match" : "not match") );
}

输出将为

100 - 200 mg : match
100 (+/-) units : not match