简体   繁体   中英

Regular Expression without braces

i have the following sample cases :

  • 1) "Sample"
  • 2) "[10,25]"

I want to form a(only one) regular expression pattern, to which the above examples are passed returns me "Sample" and "10,25" .

Note: Input strings do not include Quotes.

I came up with the following expression (?<=\\[)(.*?)(?=\\]) , this satisfies the second case and retreives me only "10,25" but when the first case is matched it returns me blank. I want "Sample" to be returned? can anyone help me.

C#.

As far as I can tell, the below regex should help:

Regex regex = new Regex(@"^\w+|[[](\w)+\,(\w)+[]]$");

This will match multiple words, or 2 words (alphanumeric) separated by commas and inside square brackets.

here you go, a small regex using a positive lookbehind, sometime these are very handy

Regex

(?<=^|\[)([\w,]+)

Test string

Sample
[10,25]

Result

MATCH 1

  1. [0-6] Sample

MATCH 2

  1. [8-13] 10,25

try at regex101.com


if " is included in your original string, use this regex, this will look for " mark as well, you may choose to remove ^| from lookup if " mark is always included or you may choose to leave it as it is if your text has combination of with and without " marks

Regex

(?<=^|\[|\")([\w,]+)

try at regex101.com

One Java example:

//          String input = "Sample"; 
            String input = "[10,25]";
            String text = "[^,\\[\\]]+";

            Pattern pMod = Pattern.compile("(" + text + ")|(?>\\[(" + text + "," + text + ")\\])");
            Matcher mMod = pMod.matcher(input);
            while (mMod.find()) {
                if(mMod.group(1) != null) {
                    System.out.println(mMod.group(1));
                }
                if(mMod.group(2)!=null) {
                    System.out.println(mMod.group(2));
                }               
            }

if input is "[hello&bye,25|35]", then the output is hello&bye,25|35

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM