在方括号和非括号上分割字符串

时间:2019-04-24 11:01:32

标签: javascript regex

这是正则表达式问题 我想分割一个字符串

apple[orange] papya [mango] [grapes]

进入此数组 ['apple','[orange]','papaya','[mango]','[grapes]']

我已经尝试过这样 "apple[orange] papya [mango] [grapes]".match(/[^[\]]+(?=])/g) 但是它只返回括号内的内容

1 个答案:

答案 0 :(得分:5)

您可以尝试以下正则表达式:public static void sendEmail(String attachmentFile, String message, Context context) { try { String email = "myname@gmail.com"; String subject = "subject"; final Intent intent = new Intent(android.content.Intent.ACTION_SEND); intent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{email}); intent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject); intent.setType("image/*"); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // generate URI, I defined authority as the application ID in the Manifest, the last param is file I want to open File file = new File(attachmentFile); Uri uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID, file); StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); StrictMode.setVmPolicy(builder.build()); intent.putExtra(Intent.EXTRA_STREAM, uri); intent.putExtra(android.content.Intent.EXTRA_TEXT, message); context.startActivity(Intent.createChooser(intent, "Sending email...")); /* PackageManager pm = context.getPackageManager(); if (intent.resolveActivity(pm) != null) { context.startActivity(Intent.createChooser(intent, "Sending email...")); } */ } catch (Throwable t) { Log.d(TAG, t.getLocalizedMessage()); } 可以匹配任意数量的不闭合闸和闭合括号的开括号,括号用于捕获拆分中的匹配项。

/(\[[^\]]+\])/

修剪用于滤除您也可以使用的空白

var input = 'apple[orange] papya [mango] [grapes]';
console.log(input.split(/(\[[^\]]+\])/).filter(s => s.trim()));