简体   繁体   English

正则表达式精确或包含

[英]Regular expression for exactly OR contains

I want to send a location to Google Geocoding API, therefore I want to replace any space or comma in the text (as it can be received) with +.我想向 Google Geocoding API 发送一个位置,因此我想用 + 替换文本中的任何空格或逗号(因为它可以接收)。

For example, all those samples should return Glentworth+Ireland :例如,所有这些样本都应该返回 Glentworth+Ireland

Glentworth Ireland格兰特沃思爱尔兰

Glentworth,Ireland爱尔兰格兰特沃思

Glentworth, Ireland爱尔兰格兰特沃思

I tried with: place.replaceAll("/\\\\\\\\b ,/\\\\\\\\b|[ ,]", "+") .我试过: place.replaceAll("/\\\\\\\\b ,/\\\\\\\\b|[ ,]", "+") But I still got in the latest case Glentworth++Ireland (where it's should be one plus only).但我仍然在最新的案例中得到了 Glentworth++Ireland(它应该只是一加)。

So the question is how can I replace " ," with plus (and just if <space>, not exist exact to replace the space/comma with plus) ?所以问题是我怎样才能用加号替换“,”(如果<space>,不存在完全用加号替换空格/逗号)?

(Or in other words, how can I be sure the place is ready to send as request to the API). (或者换句话说,我如何确定该地点已准备好作为请求发送到 API)。

PS Of course, I can do it with to replaces, but not want! PS当然,我可以用替换来做到这一点,但不想要!

Simply you can do it with two replaces: at first you replace any "," to " ", and next you replace all spaces to one plus.很简单,你可以用两次替换来完成:首先将任何“,”替换为“”,然后将所有空格替换为一个加号。 If you want to do it with one replace, you can use "[\\,\\s]\\s*"如果你想一次替换,你可以使用"[\\,\\s]\\s*"

If you want to replace any sequence of commas and spaces in your string with a single plus sign, you can do this:如果你想用一个加号替换字符串中的任何逗号和空格序列,你可以这样做:

place.replaceAll("[, ]+", "+")

[, ] is a character class containing comma and space, that means it will match either a comma or a space. [, ]是包含逗号和空格的字符类,这意味着它将匹配逗号或空格。

+ means "the preceding item one or more times". +表示“前面的项目一次或多次”。

So [, ]+ means "one or more occurrences of commas and/or spaces".所以[, ]+表示“一次或多次出现逗号和/或空格”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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