javascript正则表达式 - 从输出中删除额外的斜杠

时间:2018-05-07 07:35:46

标签: javascript regex

从json文件读取后,我在模式上使用RegExp。

json file : 
patternToSearch : {
"test" : "/^test/g"
}

在js文件中,我使用此模式匹配字符串

var patternToMatch = "testing";

var pattern = new RegExp(file.patternToSearch[test]);
console.log(pattern.test(patternToMatch);

我将输出视为false,而不是/^test/g该模式将显示为/\/^test\/g/

无法移除额外的板条。有人可以帮助我吗?

4 个答案:

答案 0 :(得分:1)

在您的代码中@EnableWebSecurity @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired AppConfig appConfig; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/v2/**") .hasAuthority(MY_AUTHORITY).anyRequest().authenticated() .and() .httpBasic(); } @Autowired public void configureSecurityManager(AuthenticationManagerBuilder authManagerBuilder) throws Exception { new InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder>() .withUser(appConfig.getCredentials().getUserName()) .password(appConfig.getCredentials().getPassword()) .authorities(MY_AUTHORITY) .and() .configure(authManagerBuilder); } } 未在您的案例中定义。

test

您必须将var pattern = new RegExp(file.patternToSearch[test]); ^ ^ 替换为test。 所以代码看起来应该像

"test"

它也有效:

var pattern = new RegExp(file.patternToSearch["test"]);

答案 1 :(得分:1)

试试这个:

var pattern = new RegExp(file.patternToSearch[test].replace(/^\/|\/$/g,''));

,因为:

console.log(`/\/^test\/g/`.replace(/^\/|\/$/g, ''))

\/无关紧要。

我不知道为什么你没有使用patternToSearch[test]收到错误。除非你定义了变量patternToSearch.test,否则它应该是test

所以我建议你试试这个:

var pattern = new RegExp(file.patternToSearch.test.replace(/^\/|\/$/g,''));

答案 2 :(得分:1)

您从其他答案中看到,访问File file1 = new File(selectedPath1); String urlString = "url"; try { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(urlString); FileBody bin1 = new FileBody(file1); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("uploadedfile", bin1); reqEntity.addPart("Firstname", new StringBody("Firstname")); reqEntity.addPart("Mobilenumber", new StringBody("Mobilenumber")); post.setEntity(reqEntity); HttpResponse response = client.execute(post); resEntity = response.getEntity(); final String response_str = EntityUtils.toString(resEntity); if (resEntity != null) { Log.i("RESPONSE",response_str); runOnUiThread(new Runnable(){ public void run() { try { res.setTextColor(Color.GREEN); res.setText("n Response from server : n " + response_str); Toast.makeText(getApplicationContext(),"Upload Complete. Check the server uploads directory.", Toast.LENGTH_LONG).show(); } catch (Exception e) { e.printStackTrace(); } } }); } } catch (Exception ex){ Log.e("Debug", "error: " + ex.getMessage(), ex); } 而不将其视为字符串是错误的。此外,您应该将原始正则表达式分为两部分: patterns flags 然后在key构造函数中使用它们:

RegExp

但在此之前,您必须确保令牌和转义字符被双重转义。

答案 3 :(得分:0)

试试此代码

new RegExp("\^test", "g")

我是从here

得到的