-3

I need to allow white spaces between words but not allow white spaces between characters. for Example - "ABC X", "ABC XC" are allowed but "C X", "ABC X C" are not.

Requirement is "No letter followed by space followed by letter"

This needs to work for Spanish characters as well.

Should work in - Java and Javascript I've seen quite few questions (like regular expression to allow spaces between words) but they either allow space or not allow space anywhere string.

I tried with - > /(.)[^ ](.){1,}/ and (\S\s+\S)

I'm new to regEx and not sure how to proceed. Will be great help if somebody can provide answer or some hint to achieve this.

Thanks, YK

Community
  • 1
  • 1
YogeshK
  • 47
  • 11
  • like this `^(?!.*\b\w\b\s+\w\b).*` ? – Avinash Raj Oct 21 '15 at 05:02
  • Welcome to StackOverflow! Show us what you've tried, and tell us what language you're doing this in so we know the quirks of the regex parser, and we'll be happy to help. – ghoti Oct 21 '15 at 05:04
  • What is a "word"? Normally a single character counts as a word. In your examples a single character seems sometimes acceptable and sometimes not. You ought to clarify your requirements to get a good answer. –  Oct 21 '15 at 05:33
  • When you say word, do you mean something that I would find in a dictionary? – d0nut Oct 21 '15 at 05:35
  • @AvinashRaj this one works for all except all specials Spanish characters. I need to support Spanish character as well – YogeshK Oct 21 '15 at 06:30
  • This one `(\s|^)\S\s+\S(\s|$)` supports Spanish characters as well but it's reverse of what I need. I think I will go this. – YogeshK Oct 21 '15 at 06:37
  • @YogeshK: Try `\b\S\s+\S\b`. In Java, you'd also need to use a `(?U)` modifier for the `\b` to work correctly and double escape the backslashes. What programming language are you using in fact? Both Java and JS? Do you really need 1 regex for two? – Wiktor Stribiżew Oct 21 '15 at 06:47
  • Can results of `(\s|^)\S\s+\S(\s|$)` be negated ? – YogeshK Oct 21 '15 at 06:51
  • @stribizhev yes, same RegEx will be used in JS(backbone.js) in front end and Java at back end. – YogeshK Oct 21 '15 at 06:53
  • Use `!` operator with `string.matches` in Java and `RegExp.test` in JS. Note that the whole string should match by Java `matches`, thus you would need to use something like `rx = ".*" + regex + ".*"`. – Wiktor Stribiżew Oct 21 '15 at 06:55
  • Thanks, all for your help. I will be using `(\s|^)\S\s+\S(\s|$)` with negative check – YogeshK Oct 21 '15 at 07:08

1 Answers1

1

Answering my own question here. (\s|^)\S\s+\S(\s|$) will match with all the criteria mentioned in the question.
As we need to restrict these format, negate the result of expression match.

Also for java, use matcher.find() instead of matcher.matches() to get desire result as it attempts to find the next subsequence of the input sequence that matches the pattern.

YogeshK
  • 47
  • 11